pop() and push() 实现栈的效果(LIFO)
- push()从数组的末尾依此添加元素,返回新的数组
- pop() 从数组末尾移除最后一项,返回移除项,减少数组的length值
- 如果为空数组 pop()方法返回[]
shift() and unshift() 实现队列的效果(FIFO)
- shift() 删除数组第一项并返回该项的值
- unshift() 从数组前端添加任意个数组项并返回新数组的
长度。
pop() and unshift() 性能
由于unshift 方法是从数组前端插入新的项,所以每次都要把现有元素往下移一个位置。效率非常慢
如果非要实现unshift的效果 可以用 reserve(), push(), reserve() 代替 先将数组反转, 添加新元素之后,再反转达到unshift的效果
- 上面结论所言情况为:只在数组中进行前端插入操作,而不进行其他操作的情况。但在实际情况中,不单单只有插入操作。实际应用中,可根据需求结合push,unshift使用
- 另外 concat() + reverse() 方法也可以实现 unshift() 效果
const a = [1,2,3, 4,5]
a.unshift(2,4,6)
// 8 --> 新数组长度
console.log(a)
// [2,4,6,1,2,3,4,5]
Array.prototype.find() and Array.prototype.findIndex()
// a 为一个稀疏数组
const a = [1,2,,,5,6]
a.find((value, index) => {
console.log('value: ' + value + ' and index: '+ index)
})
// index: 0 value: 1
// index: 1 value: 2
// index: 2 value: undefined
// index: 3 value: undefined
// index: 4 value: 5
// index: 5 value: 6
- find 方法对数组中的每一项元素执行一次 callback 函数
- 注意 callback 函数会为数组中的每个索引调用即从 0 到 length - 1,而不仅仅是那些被赋值的索引
- 当在回调中删除数组中的一个值时,当访问到这个位置时,其传入的值时 undefined
// find 方法执行时,删除数组中元素
a.find((value, index) => {
if(index == 0) {
console.log('Deleting a[5] with value ' + a[5])
delete a[5]
}
console.log('Visited index ' + index + ' with value ' + value);
})
// "Deleting a[5] with value 6"
// "Visited index 0 with value 1"
// "Visited index 1 with value 2"
// "Visited index 2 with value undefined"
// "Visited index 3 with value undefined"
// "Visited index 4 with value 5"
// "Visited index 5 with value undefined"
- 在find 方法开始执行后添加到数组的新元素将不会被callback 函数访问到。
a.find((value, index) => {
if(index == 0) {
a[6] = 7
console.log('Adding a[6] with value ' + a[6])
}
console.log('Visited index ' + index + ' with value ' + value);
})
// "Adding a[6] with value 7"
// "Visited index 0 with value 1"
// "Visited index 1 with value 2"
// "Visited index 2 with value undefined"
// "Visited index 3 with value undefined"
// "Visited index 4 with value 5"
// "Visited index 5 with value 6"
- Array.prototype.findIndex() 返回第一个满足提供测试数组的下标,如果没有满足条件的则返回-1
const a = [1,2,4,5,3]
let findindex = a.findIndex((value, index)=>{
return value == undefined
})
console.log(findindex)
// -1