Array queue method

The access rule of the queue data structure is FIFO (Fist-In-Fist-Out, first in first out). The queue adds items to the end of the list and removes items from the front of the list.
shift(); Remove the first item in the array and return the item, and reduce the length of the array by 1. By combining the shift() and push() methods, you can use an array like a queue.

//先进先出
var colors = new Array(); //创建一个数组
var count = colors.push("red","green"); //推入两项
alert(count)//2

count = colors.push("black"); //推入另一项
alert(count)//3

var item = colors.shift(); //取得第一项
alert(item); //"red"
alert(colors.length)//2

ES also provides an unshift() method for arrays. unshift() and shift() have the opposite purpose: it can add any number of items to the front of the array and return the length of the new array. Using the unshift() and pop() methods at the same time, you can simulate the queue in the opposite direction, that is, adding items to the front of the array and removing items from the end of the array.

//后进后出
var colors = new Array(); //创建一个数组
var count = colors.unshift("red","green"); //推入两项
alert(count)//2

count = colors.unshift("black"); //推入另一项
alert(count)//3

var item = colors.pop(); //取得第一项
alert(item); //"green"
alert(colors.length)//2

Related knowledge:
stack data structure

Guess you like

Origin blog.csdn.net/weixin_42549581/article/details/104151136