unshift方法在零索引处添加元素,并将连续索引处的值上移,然后返回数组的长度。
该push()方法将元素末尾添加到数组中并返回该元素。此方法更改数组的长度。
let fruits = ['apple', 'mango', 'orange', 'kiwi'];
let fruits2 = ['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慢,因为一旦添加第一个元素,它还需要将所有元素向左移。