Javascript 连接 N 个数组的最有效方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5080028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the most efficient way to concatenate N arrays?
提问by Leonid
What is the most efficient way to concatenate N arrays of objects in JavaScript?
在 JavaScript 中连接 N 个对象数组的最有效方法是什么?
The arrays are mutable, and the result can be stored in one of the input arrays.
数组是可变的,结果可以存储在输入数组之一中。
回答by Tim Down
If you're concatenating more than two arrays, concat()
is the way to go for convenience and likely performance.
如果您连接两个以上的数组,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];
For concatenating just two arrays, the fact that push
accepts multiple arguments consisting of elements to add to the array can be used instead to add elements from one array to the end of another without producing a new array. With slice()
it can also be used instead of concat()
but there appears to be no performance advantage from doing this.
对于仅连接两个数组,可以使用push
接受由要添加到数组的元素组成的多个参数这一事实来代替将一个数组中的元素添加到另一个数组的末尾,而无需生成新数组。有了slice()
它也可以用来代替concat()
,但似乎从没有这样做,性能上的优势。
var a = [1, 2], b = ["x", "y"];
a.push.apply(a, b);
console.log(a); // [1, 2, "x", "y"];
In ECMAScript 2015 and later, this can be reduced even further to
在 ECMAScript 2015 及更高版本中,这可以进一步减少到
a.push(...b)
However, it seems that for large arrays (of the order of 100,000 members or more), the technique passing an array of elements to push
(either using apply()
or the ECMAScript 2015 spread operator) can fail. For such arrays, using a loop is a better approach. See https://stackoverflow.com/a/17368101/96100for details.
然而,似乎对于大型数组(100,000 个成员或更多),将元素数组传递给push
(使用apply()
或 ECMAScript 2015 扩展运算符)的技术可能会失败。对于此类数组,使用循环是更好的方法。有关详细信息,请参阅https://stackoverflow.com/a/17368101/96100。
回答by ninjagecko
[].concat.apply([], [array1, array2, ...])
edit: proof of efficiency: http://jsperf.com/multi-array-concat/7
编辑:效率证明:http: //jsperf.com/multi-array-concat/7
edit2: 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.)
edit2:Tim Supinie 在评论中提到这可能会导致解释器超出调用堆栈大小。这可能取决于 js 引擎,但至少我在 Chrome 上也遇到了“超出最大调用堆栈大小”的情况。测试用例:[].concat.apply([], Array(300000).fill().map(_=>[1,2,3]))
. (我在使用当前接受的答案时也遇到了同样的错误,因此人们正在预测此类用例或为其他人构建库,无论您选择哪种解决方案,都可能需要进行特殊测试。)
回答by Duncan Luk
For people using ES2015 (ES6)
对于使用 ES2015 (ES6) 的人
You can now use the Spread Syntax to concatenate arrays:
您现在可以使用 Spread 语法来连接数组:
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]
回答by dogbane
The concat()
method is used to join two or more arrays. It does not change the existing arrays, it only returns a copy of the joined arrays.
该concat()
方法用于连接两个或多个数组。它不会更改现有数组,它只返回连接数组的副本。
array1 = array1.concat(array2, array3, array4, ..., arrayN);
回答by Burnee
Use Array.prototype.concat.apply to handle multiple arrays' concatenation:
使用 Array.prototype.concat.apply 处理多个数组的串联:
var resultArray = Array.prototype.concat.apply([], arrayOfArraysToConcat);
Example:
例子:
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]
回答by artnikpro
If you are in the middle of piping the result through map/filter/sort etc and you want to concat array of arrays, you can use reduce
如果您正在通过 map/filter/sort 等管道传输结果,并且想要连接数组数组,则可以使用 reduce
let sorted_nums = ['1,3', '4,2']
.map(item => item.split(',')) // [['1', '3'], ['4', '2']]
.reduce((a, b) => a.concat(b)) // ['1', '3', '4', '2']
.sort() // ['1', '2', '3', '4']
回答by David
For array of multiple arrays and ES6, use
对于多个数组和 ES6 的数组,使用
Array.prototype.concat(...arr);
For example:
例如:
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 ]
回答by chinmayan
Now we can combine multiple arrays using ES6
Spread
.
Instead of using concat()
to concatenate arrays, try using the spread syntax to combine multiple arrays into one flattened array.
eg:
现在我们可以使用ES6
Spread
. 不要使用concat()
连接数组,而是尝试使用展开语法将多个数组合并为一个扁平数组。例如:
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]
回答by Th1
solved like this.
像这样解决了。
let arr = [[1, 2], [3, 4], [5, 6]];
console.log([].concat(...arr));
回答by Dmitri Farkov
Easily with the concat function:
轻松使用 concat 功能:
var a = [1,2,3];
var b = [2,3,4];
a = a.concat(b);
>> [1,2,3,2,3,4]