javascript 中 push() 和 unshift() 方法的区别

javascriptobject oriented programmingfront end technology

unshift 方法将元素添加到第零索引处,并将连续索引处的值向上移动,然后返回数组的长度。

push() 方法将末尾的元素添加到数组并返回该元素。此方法更改数组的长度。

示例

let fruit = ['apple', 'mango', 'orange', 'kiwi'];
let fruit2 = ['apple', 'mango', 'orange', 'kiwi'];
console.log(fruits.push("pinapple"))
console.log(fruits2.unshift("pinapple"))
console.log(fruits)
console.log(fruits2)

输出

5
5
[ 'apple', 'mango', 'orange', 'kiwi', 'pinapple' ]
[ 'pinapple', 'apple', 'mango', 'orange', 'kiwi' ]

请注意,此处两个原始数组均已更改。

Unshift 比 push 慢,因为一旦添加了第一个元素,它还需要取消向左移动所有元素。


相关文章