shift方法删除零位索引处的元素,并将连续索引处的值向下移位,然后返回删除的值。如果length属性为0,则返回undefined。
该pop()
方法从数组中删除最后一个元素,然后返回该元素。此方法更改数组的长度。
let fruits = ['apple', 'mango', 'orange', 'kiwi']; let fruits2 = ['apple', 'mango', 'orange', 'kiwi']; console.log(fruits.pop()) console.log(fruits2.shift()) console.log(fruits) console.log(fruits2)
输出结果
kiwi apple [ 'apple', 'mango', 'orange' ] [ 'mango', 'orange', 'kiwi' ]
请注意,两个原始数组都在这里进行了更改。
Shift比pop慢,因为一旦删除第一个元素,它还需要将所有元素向左移。