Stack method for arrays:
The stack is a LIFO (Last-in-first-out, LIFO ) data structure, where the most recently added item is first removed.
The insertion of the item in the stack (called Push-in) and the removal (called popup) occur only in one place-the top of the stack.
The ECMAScript array specifically provides the push () and Pop () methods to implement a stack-like behavior.
Push () returns the current length of the array, and POP () returns the item that was removed from the array.
Queue method
The access rules for queue data structures are FIFO (first-in-first-out, first-in, in-advance). The queue adds items at the end of the list, removing items from the front end of the list.
Using the shift () and push () methods together, you can use arrays as you would with queues.
varcolors =NewArray ();//Create an arrayvarCount = Colors.push ("Red","Green");//push in two itemsalert (count);//2Count = Colors.push ("Black");//push into another itemalert (count);//3 var item = Colors.shift (); //get the first itemalert (item);//"Red"alert (colors.length);//2
The bold line in the code uses the Shift () method to get the first item from the array, the "red"
ECMAScript also provides an array of unshift () methods for the arrays. As the name implies, Unshift () is the opposite of the use 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 to the front of the array, removing items from the end of the array, as shown in the following example.
varcolors =NewArray ();//Create an arrayvarCount = Colors.unshift ("Red","Green");//push in two itemsalert (count);//2Count = Colors.unshift ("Black");//push into another itemalert (count);//3varitem = Colors.pop ();//get the last onealert (item);//"Green"alert (colors.length);//2
Summarize:
Push () pushes from the end of the array to return the array length
Pop () out of the end of the array returns the item taken out
Shift () out of the front of the array to return the item that was taken out
Unshift () The length of the array that is pushed back from the end of the array
Some methods of JS advanced programming Array