JS数组:push vs concat

使用JS这么久, 对于JS数组的相关方法一直都是拿来就用,对于push方法更是常用。但是在一次用到contact方法的时候自问了一句: pushcontact到底有哪些区别?

先看下MDN的定义:

push:adds one or more elements to the end of an array and returns the new length of the array.
var animals = ['pigs', 'goats', 'sheep'];
console.log(animals.push('cows')); // expected output: 4
console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows"]


animals.push(['new arr']); // expected output: 5
console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows", Array(1)]
contact:The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.
var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2)); // expected output: Array ["a", "b", "c", "d", "e", "f"]
console.log(array1); // expected output: Array ["a", "b", "c"]
console.log(array2); // expected output: Array ["d", "e", "f"]

摘取重点:

  1. push方法添加元素到数组末尾,改变的是同一个数组, 返回值是添加之后数组的长度
  2. contact方法是合并两个或者多个数组,不会改变存在的数组,返回的是合并的数组

那性能会不会有区别?

环境:win8.1 chrome 63.0.3239.132

// push demo
var arr3 = [1, 2, 3];
var arr4 = [4, 5, 6];
console.time('push');
for (let index = 10000; index > 0; index--) {
  arr3.push(...arr4);
}
console.timeEnd('push'); // push: 2.39892578125ms
// contact demo
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
console.time('contact');
for (let index = 10000; index > 0; index--) {
  arr1 = arr1.concat(arr2);
}
console.timeEnd('contact'); // contact: 312.762939453125ms

在我这个环境上push+解构的性能是要好于contact的。不过对于多个数组合并的时候, contact因为返回的是新数组,可以链式下去。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值