# JavaScript 中合并数组的两种方法

```var a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
var b = [ "foo", "bar", "baz", "bam", "bun", "fun" ];```

`[1,2,3,4,5,6,7,8,9,"foo","bar","baz","bam","bun","fun"]`

## Concat

```var c = a.concat( b );

a; // [1,2,3,4,5,6,7,8,9]
b; // ["foo","bar","baz","bam","bun","fun"]

c; // [1,2,3,4,5,6,7,8,9,"foo","bar","baz","bam","bun","fun"]```

`a = b = null; // `a` and `b` can go away now`

## 循环插入

``` // `b` onto `a`
for (var i=0; i < b.length; i++) {
a.push( b[i] );
}

a; // [1,2,3,4,5,6,7,8,9,"foo","bar","baz","bam","bun","fun"]

b = null;```

```// `a` into `b`:
for (var i=a.length-1; i >= 0; i--) {
b.unshift( a[i] );
}

b; // [1,2,3,4,5,6,7,8,9,"foo","bar","baz","bam","bun","fun"]

a = null;```

## 功能上的技巧

`for` 循环是丑陋的和难以维持。我们可以做的更好吗？这是我们的第一次尝试，使用 `reduce`

```// `b` onto `a`:
a = b.reduce( function(coll,item){
coll.push( item );
return coll;
}, a );

a; // [1,2,3,4,5,6,7,8,9,"foo","bar","baz","bam","bun","fun"]

// or `a` into `b`:
b = a.reduceRight( function(coll,item){
coll.unshift( item );
return coll;
}, b );

b; // [1,2,3,4,5,6,7,8,9,"foo","bar","baz","bam","bun","fun"]```

`reduce()``reduceRight()` 是好的，但他们有点笨拙的。ES6 `=>` 箭头的函数将瘦身略有下降，但它仍然需要每项调用一个函数，这是不幸的。

```// `b` onto `a`:
a.push.apply( a, b );

a; // [1,2,3,4,5,6,7,8,9,"foo","bar","baz","bam","bun","fun"]

// or `a` into `b`:
b.unshift.apply( b, a );

b; // [1,2,3,4,5,6,7,8,9,"foo","bar","baz","bam","bun","fun"]```

```function combineInto(a,b) {
var len = a.length;
for (var i=0; i < len; i=i+5000) {
b.unshift.apply( b, a.slice( i, i+5000 ) );
}
}```

## 总结

`concat(..)` 是尝试和真实的方法相结合的两个（或更多！）阵列。但隐藏的危险是，它创造了一个新的数组，而不是修改一个现有的。

JSmiles

2583 文章
29 评论
84935 人气