有没有一种通过索引合并数组的好方法?

时间:2018-05-16 19:03:02

标签: javascript

给定两个任意数组a和b,如何将它们合并以获得以下结果:

var a = [1, 3, 5, 7];
var b = [2, 4, 6];
var c = merge(a,b); // c = [1, 2, 3, 4, 5, 6, 7]

var a = ["string1", "string2"];
var b = ["string3"];
var c = merge(a,b); // c = ["string1", "string3", "string2"]

1 个答案:

答案 0 :(得分:0)

This answer to a similar question is probably what you're looking for.

var c = a.reduce(function(arr, v, i) {
                          return arr.concat(v, b[i]); 
                       }, []);

The previous author also provided a demo here.