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.(为了连接两个数组,可以使用push
接受包含要添加到数组的元素的多个参数的事实来将元素从一个数组添加到另一个数组的末尾而不生成新数组。)
With slice()
it can also be used instead of concat()
but there appears to be no performance advantage from doing this .(使用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.(但是,似乎对于大型数组(大约100,000个成员或更多),将元素数组传递给push
(使用apply()
或ECMAScript 2015扩展运算符)的技术可能会失败。)
For such arrays, using a loop is a better approach.(对于这样的数组,使用循环是一种更好的方法。) See https://stackoverflow.com/a/17368101/96100 for details.(有关详细信息,请参阅https://stackoverflow.com/a/17368101/96100 。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…