Arrays and objects should be the most commonly used and most frequently used types in JavaScript. Array provides many commonly used methods: stack method, queue method, reorder method, operation method, position method, iteration method , etc.
1. Array stack method
The stack is a LIFO (Last-In-First-Out, later-in-first-out) data structure, that is, the latest added item is removed at the earliest. The insertion and removal of items in the stack only happens at one location - the top of the stack. ECMAScript provides push() and pop() methods for arrays, which can implement stack-like behavior. The following two figures demonstrate the stack entry and stack exit operations respectively.
The push() method can receive parameters of any data, add them one by one to the end of the array, and return the modified array length. The pop() method removes the last item from the end of the array, reducing the length value of the array
var students = [];students.push("bluce","jordan","marlon","kobe");//4 items of the stack are alert(students.length); //4alert(students[0]); //"bluce", the first item is at the bottom of the stack alert(students[1]); //"jordan"students.push("paul");alert(students.length); //5var item = students.pop(); //"paul"alert(students.length); //42. Array's queue method
The access rule of the stack data structure is LIFO (Last-In-First-Out), while the access rule of the queue data structure is FIFO (First-In-First-Out, First-In-First-Out) . The queue adds items at the end of the list and removes items from the front end of the list. The push() method is a method of adding items to the end of the array. Therefore, to simulate a queue, you only need a method to obtain items from the front end of the array - shift(), which can remove the first item in the array and return the item, and at the same time, length-1 of the array. Using the shift() and push() methods in combination, you can use arrays like you would with queues.
var students = [];students.push("bluce","jordan","marlon","kobe");//4 items of enqueue//students=["bluce","jordan","marlon","kobe"];alert(students.length); //4alert(students[0]); //"bluce", the first item is at the bottom of the stack alert(students[1]); //"jordan"students.push("paul");alert(students.length); //5//students=["bluce","jordan","marlon","kobe","paul"];var item = students.shift(); //"bluce"alert(students.length); //4//students=["jordan","marlon","kobe","paul"];In addition, ECMAScript also provides the unshift() method, which can add any item to the front end of the array and return the length of the new array. Therefore, using unshift() and pop() methods in combination, you can simulate the queue from the opposite direction, that is, add items at the front end of the array and remove items from the end of the array