Get the App
SLTechnology News&Howtos  ›  Development  › 

Case Analysis of Javascript queue method

Shulou Source: shulou.com Published: 2022-06-01 03:45:13 10月03日 Update

This article mainly introduces the relevant knowledge of "Javascript queue method case analysis". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this "Javascript queue method case analysis" article can help you solve the problem.

Javascript Array queuing method

The access rule of stack data structure is LIFO (LIFO), while the access rule of queue data structure is FIFO (first-in-first-out). The queue adds items at the end of the list and removes items from the front of the list. Because push () is a way to add items to the end of an array, all you need to simulate a queue is a way to get items from the front end of the array. The array method that does this is shift (), which removes the first item in the array and returns it, while subtracting the length of the array by 1. Using the shift () and push () methods together, you can use arrays just like queues:

Var colors=new Array (); / / create an array

Var count=colors.push ("red", "greent"); / / push two items

Alert (count); / / 2

Count=colors.push ("black"); / / push another item

Alert (count); / / 3

Alert (item); / / "red"

Alert (colors.length); / / 2

This example first uses the push () method to create an array of three color names. The shaded line in the code uses the shift () method to get the first item from the array, "red". After the first item is removed, "green" becomes the first item, "black" becomes the second item, and the array contains only two items.

ECMAScript also provides a unshift () method for arrays. As the name implies, unshift () is the opposite of shift (): it can add any item to the front of the array and return the length of the new array. Therefore, using both the unshift () and pop () methods, you can simulate the queue in the opposite direction, adding items at the front of the array and removing items from the end of the array, as shown in the following example:

Var colors=new Array (); / / create an array

Alert (count); / / 2

Alert (count); / / 3

Alert (item); / / "green"

Alert (colors.length); / / 2

This is the end of the introduction to "Javascript queue method instance Analysis". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Array method queue front end instance instance analysis analysis end knowledge example at the same time data data structure structure industry rules length first out different practical Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Redmi Docker MariaDB NVidia