如何以变异的方式在JS中连接数组?

Kar*_*lak 5 javascript concatenation

在JS中以变异方式连接数组的最佳方法是什么?我的问题:

var a = [1,2,3]
var b = a;
a = a.concat([4,5,6]) //<-- typical way of array concatenation in JS
console.log(a) //[1,2,3,4,5,6]
console.log(b) //[1,2,3] <-- I'd like it to be the same like a here
Run Code Online (Sandbox Code Playgroud)

我当然可以使用一些循环,但我想知道是否有更快更清洁的方法来实现它.

Dan*_*sky 13

push变异数组,但它需要参数序列,所以我们使用apply:

var a = [1,2,3]
var b = a
a.push.apply(a, [4,5,6])
console.log(a) //=> [1, 2, 3, 4, 5, 6]
console.log(b) //=> [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

在ES6中,您可以使用扩展运算符...:

a.push(...[4, 5, 6])
Run Code Online (Sandbox Code Playgroud)