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

查看:27
本文介绍了连接 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天全站免登陆