如何在JavaScript中压缩两个数组?(复制)

时间:2021-09-07 21:17:30

This question already has an answer here:

这个问题已经有了答案:

I have 2 arrays:

我有2个数组:

var a = [1, 2, 3]
var b = [a, b, c]

What I want to get as a result is:

我想得到的结果是:

[[1, a], [2, b], [3, c]]

It seems simple but I just can't figure out.

这似乎很简单,但我就是想不明白。

I want the result to be one array with each of the elements from the two arrays zipped together.

我希望结果是一个数组,两个数组中的每个元素都压缩在一起。

2 个解决方案

#1


97  

Use the map method:

使用地图的方法:

var a = [1, 2, 3]
var b = ['a', 'b', 'c']

var c = a.map(function(e, i) {
  return [e, b[i]];
});

console.log(c)

DEMO

演示

#2


5  

Array.prototype.map() is not supported in older browsers

在较旧的浏览器中不支持Array.prototype.map()。

Feature       Chrome Firefox (Gecko) Internet Explorer  Opera Safari
Basic support (Yes) 1.5      (1.8)   9                  (Yes) (Yes)

Here is an alternative which works everywhere.

这里有一个可以在任何地方工作的替代方案。

var a = [1, 2, 3],
    b = ['a', 'b', 'c'];

var c = [];
for (var i = 0; i < a.length; i++){
   c.push([a[i], b[i]]);
}
console.log(c); // [[1, "a"], [2, "b"], [3, "c"]]

#1


97  

Use the map method:

使用地图的方法:

var a = [1, 2, 3]
var b = ['a', 'b', 'c']

var c = a.map(function(e, i) {
  return [e, b[i]];
});

console.log(c)

DEMO

演示

#2


5  

Array.prototype.map() is not supported in older browsers

在较旧的浏览器中不支持Array.prototype.map()。

Feature       Chrome Firefox (Gecko) Internet Explorer  Opera Safari
Basic support (Yes) 1.5      (1.8)   9                  (Yes) (Yes)

Here is an alternative which works everywhere.

这里有一个可以在任何地方工作的替代方案。

var a = [1, 2, 3],
    b = ['a', 'b', 'c'];

var c = [];
for (var i = 0; i < a.length; i++){
   c.push([a[i], b[i]]);
}
console.log(c); // [[1, "a"], [2, "b"], [3, "c"]]