The JavaScript array specifically provides the push and pop () methods to implement a stack-like behavior. Take a look at the following example:
var colors=new Array (); Create an array
var Count=colors.push ("Red", "green"); Pushes two entries to return the length of the modified array
alert (count); 2 Returns the length of the modified array
var item=colors.pop (); Get the last one
alert (item); "Green"
alert (colors.length); 1
Queue method:
Using the shift () and push () methods together, you can use arrays as you would with queues:
var colors=new Array ();
var Count=colors.push ("Red", "green"); Push in two items
alert (count); 2
Count= Colors.push ("Black"); Add an item from the end of the array, at which point the order of the array is: "Red", "green", "black"
alert (count); 3
var item=colors.shift (); Get the first item
alert (item); "Red"
alert (colors.length); 2
As you can see from the example:
Shift () Method: Removes the first item in the array and returns the item
Push () Method: Add an item from the end of the array
If you want to do the opposite, you can use the
Unshift () Method: Add an item to the front of the array
Pop () Method: Remove an item from the end of the array
var colors=new Array ();
var count=colors.unshift ("Red", "green");//push in two
alert (count); 2
Count=colors.unshift ("Black"); Add items from the front of the array, at which point the order of the array is: "Black", "red", "green"
alert (count); 3
var item=colors.pop ();
alert (item); Remove and return the last item "green"
From the above two sets of examples, we can clearly see the use of these two sets of methods.
In the JavaScript array, the SHIFT () and push (), Unshift (), and Pop () action methods use the