假设我有四个现有数组:
var one = ["apple","banana","berry"];
var two = ["fobar", "barfoo", "farboo"];
var three = [13, 421];
var four = ["seven", "eight", "eleven"];
如何将它们合并为一个数组并以最简单的方式返回? 我得到的是
var result = [1、2、3、4];
导致
|-----------------------------|
| apple | banana | berry |
| foobar | barfoo | farboo |
| 13 | 421 | |
| seven | eight | eleven |
|-----------------------------|
但是,我真正需要的是这个
|------------------------------------|
| apple | foobar | 13 | seven |
| banana | barfoo | 421 | eight |
| berry | farboo | | eleven |
|------------------------------------|
答案 0 :(得分:1)
JavaScript没有多维数组,它具有数组数组。
如果您还没有one
,two
,three
,four
数组,则可以使用单个嵌套文字来实现:
var result = [
["apple", "fobar", 13, "seven"],
["banana", "barfoo", 421, "eight"],
["berry", undefined, "eleven"]
];
实时示例:
var result = [
["apple", "fobar", 13, "seven"],
["banana", "barfoo", 421, "eight"],
["berry", "farboo", undefined, "eleven"]
];
console.log(result);
.as-console-wrapper {
max-height: 100% !important;
}
如果您已经拥有它们,因为它们是列值的数组,并且显然您希望子数组是行值,所以需要循环:
var result = [];
for (var i = 0; i < 3; ++i) {
result[i] = [
one[i], two[i], three[i], four[i]
];
}
实时示例:
var one = ["apple","banana","berry"];
var two = ["fobar", "barfoo", "farboo"];
var three = [13, 421];
var four = ["seven", "eight", "eleven"];
var result = [];
for (var i = 0; i < 3; ++i) {
result[i] = [
one[i], two[i], three[i], four[i]
];
}
console.log(result);
.as-console-wrapper {
max-height: 100% !important;
}
答案 1 :(得分:1)
尝试
var output = one.map(function(e,i){
return [e].concat([two, three, four].map(function(f){
return f[i] === undefined ? '': f[i];
}))
})
console.info(output);