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];
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"];
In ECMAScript 2015 and later, this can be reduced even further to
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/96100 for details.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…