连接N个数组的最有效方法是什么? [英] What is the most efficient way to concatenate N arrays?

查看:130
本文介绍了连接N个数组的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中连接N个对象数组的最有效方法是什么?

What is the most efficient way to concatenate N arrays of objects in JavaScript?

数组是可变的,结果可以存储在其中一个输入数组中。

The arrays are mutable, and the result can be stored in one of the input arrays.

推荐答案

如果要连接两个以上的数组, concat() 是要走的路为了方便和可能的表现。

If you're concatenating more than two arrays, concat() is the way to go for convenience and likely performance.

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(),但这样做似乎没有性能优势

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.

var a = [1, 2], b = ["x", "y"];
a.push.apply(a, b);
console.log(a); // [1, 2, "x", "y"];

在ECMAScript 2015及更高版本中,这可以进一步减少到

In ECMAScript 2015 and later, this can be reduced even further to

a.push(...b)

然而,似乎对于大型数组(大约100,000个成员或更多),将元素数组传递给 push 的技术(使用 apply()或ECMAScript 2015传播运算符)可能会失败。对于这样的数组,使用循环是一种更好的方法。有关详细信息,请参见 https://stackoverflow.com/a/17368101/96100

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/96100 for details.

这篇关于连接N个数组的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆