在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
当前回答
现在我们可以使用ES6 Spread组合多个数组。 不要使用concat()来连接数组,而是尝试使用spread语法将多个数组组合成一个扁平数组。 例如:
var a = [1,2];
var b = [3,4];
var c = [5,6,7];
var d = [...a, ...b, ...c];
// resulting array will be like d = [1,2,3,4,5,6,7]
其他回答
现在我们可以使用ES6 Spread组合多个数组。 不要使用concat()来连接数组,而是尝试使用spread语法将多个数组组合成一个扁平数组。 例如:
var a = [1,2];
var b = [3,4];
var c = [5,6,7];
var d = [...a, ...b, ...c];
// resulting array will be like d = [1,2,3,4,5,6,7]
如果要连接两个以上的数组,为了方便和可能的性能,concat()是最好的方法。
var a = [1, 2], b = ["x", "y"], c = [true, false];
var d = a.concat(b, c);
console.log(d); // [1, 2, "x", "y", true, false];
对于仅连接两个数组,可以使用push接受多个由要添加到数组的元素组成的参数来将元素从一个数组添加到另一个数组的末尾,而无需生成新数组。对于slice(),它也可以用来代替concat(),但这样做似乎没有性能优势。
var a = [1, 2], b = ["x", "y"];
a.push.apply(a, b);
console.log(a); // [1, 2, "x", "y"];
在ECMAScript 2015及以后的版本中,可以进一步简化为
a.push(...b)
然而,对于大型数组(100,000成员的数量级或更多),将元素数组传递给push(使用apply()或ECMAScript 2015展开操作符)的技术可能会失败。对于这样的数组,使用循环是更好的方法。详情见https://stackoverflow.com/a/17368101/96100。
[].concat.apply([], [array1, array2, ...])
效率证明:http://jsperf.com/multi-array-concat/7
Tim Supinie mentions in the comments that this may cause the interpreter to exceed the call stack size. This is perhaps dependent on the js engine, but I've also gotten "Maximum call stack size exceeded" on Chrome at least. Test case: [].concat.apply([], Array(300000).fill().map(_=>[1,2,3])). (I've also gotten the same error using the currently accepted answer, so one is anticipating such use cases or building a library for others, special testing may be necessary no matter which solution you choose.)
concat()方法用于连接两个或多个数组。它不会更改现有数组,只返回已连接数组的副本。
array1 = array1.concat(array2, array3, array4, ..., arrayN);
用Push合并数组:
Const array1 = [2,7,4]; Const array2 = [3,5,9]; array1.push(…array2); console.log (array1)
使用Concat和Spread运算符: Const array1 = [1,2]; Const array2 = [3,4]; //方法1:Concat Const combined1 =[]。concat (array1 array2); //方法二:Spread Const combined2 =[…]array1……array2); console.log (combined1); console.log (combined2);