JavaScript中push()和unshift()方法之间的区别
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慢,因为一旦添加第一个元素,它还需要将所有元素向左移。
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短