栈和队列
1. 栈
栈是一种LIFO(后进先出)的数据结构,也就是最新添加的项最早被移除。
push()方法可以将一个或多个元素推入数组的末尾位置,pop()方法可以将一个元素从数组的末尾位置移除出去。
2. 队列
队列是一种LIFO(先进先出)的数据结构。
unshift()方法可以将一个或多个元素添加到数组最前端,shift()方法可以将一个元素从数组的最前端移除出去。
var arr = ["red", "green", "blue"];
// 栈方法
// push()末尾添加 pop()末尾删除
console.log(arr.push("yellow")); // 返回新数组长度
console.log(arr); // ["red", "green", "blue", "yellow"]
console.log(arr.pop()); // 返回被删除的那个元素
console.log(arr); // ["red", "green", "blue"]
var arr2 = ["Chinese", "Math", "English"];
// 队列方法
// unshift()头部添加 shift()头部删除
console.log(arr2.unshift("new lesson")); // 返回新数组长度
console.log(arr2); // ["new lesson", "Chinese", "Math", "English"]
console.log(arr2.shift()); // 返回被删除的那个元素
console.log(arr2); // ["Chinese", "Math", "English"]