js push、push.apply 和 cancat 的区别

1.push  添加到数组的末尾 改变原数组

let temparr = [1,2,3,4];
temparr.push(5)
console.log(temparr) //[ 1, 2, 3, 4, 5 ] 

他会把追加的数组作为元素的某一项添加到末尾

temparr.push([6,7])
console.log(temparr)//[ 1, 2, 3, 4, [ 6, 7 ] ]

2. cancat 不改变原数组。concat合并数组之后,返回值才是新数组,并且可以合并两个及其以上的数组

let temparr2 = temparr.concat([7,8])
console.log(temparr2)//[ 1, 2, 3, 4, 7, 8 ]

3.push.apply合并数组是把后一个数组的值依次push进前一个数组,使前一个数组发生改变,并且只能两个数组之间发生合并。

arr1.push.apply(arr1,arr2)
console.log(arr1) //[ 1, 2, 3, 4, 4, 5, 6, 7 ]

push.apply 同Array.prototype.push.apply 。Array.prototype.push.apply 性能更好一些

猜你喜欢

转载自blog.csdn.net/meetlunay/article/details/90633036
今日推荐