在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
在JavaScript中连接N个对象数组的最有效的方法是什么?
数组是可变的,结果可以存储在一个输入数组中。
当前回答
新回答
对于多个数组和ES6的数组,使用
arr.flat();
例如:
const arr = [[1, 2, 3], [4, 5, 6], [7, 8 ,9]];
const newArr = arr.flat();
// output: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
这将适用于节点> 11和现代浏览器。
旧的答案
(把它留在这里,以防旧版本的节点需要它):
对于多个数组和ES6的数组,使用
Array.prototype.concat(...arr);
例如:
const arr = [[1, 2, 3], [4, 5, 6], [7, 8 ,9]];
const newArr = Array.prototype.concat(...arr);
// output: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
其他回答
concat()方法用于连接两个或多个数组。它不会更改现有数组,只返回已连接数组的副本。
array1 = array1.concat(array2, array3, array4, ..., arrayN);
这样解决。
let arr = [[1, 2], [3, 4], [5, 6]];
console.log([].concat(...arr));
[].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.)
使用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函数:
var a = [1,2,3];
var b = [2,3,4];
a = a.concat(b);
>> [1,2,3,2,3,4]