在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
当前回答
用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);
其他回答
这样解决。
let arr = [[1, 2], [3, 4], [5, 6]];
console.log([].concat(...arr));
使用Array.prototype.concat.apply来处理多个数组的连接:
var resultArray = Array.prototype.concat.apply([], arrayOfArraysToConcat);
例子:
var a1 = [1, 2, 3],
a2 = [4, 5],
a3 = [6, 7, 8, 9];
Array.prototype.concat.apply([], [a1, a2, a3]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
[].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.)
似乎正确答案在不同的JS引擎中有所不同。以下是我从ninjagecko的答案中链接的测试套件中得到的结果:
[] .concat。apply在Windows和Android的Chrome 83中最快,其次是reduce(慢56%); 循环concat在Mac的Safari 13中是最快的,其次是reduce(大约慢13%); reduce在iOS上的Safari 12中是最快的,其次是循环concat(慢40%); elementwise push在Windows上的Firefox 70中最快,其次是[].concat。应用(速度慢30%)。
对于使用ES2015 (ES6)的用户
你现在可以使用扩展语法来连接数组:
const arr1 = [0, 1, 2],
arr2 = [3, 4, 5];
const result1 = [...arr1, ...arr2]; // -> [0, 1, 2, 3, 4, 5]
// or...
const result2 = [...arr2, ...arr1]; // -> [3, 4, 5, 0, 1, 2]