假设我有四个现有数组:
var one = ["apple","banana","berry"];
var two = ["fobar", "barfoo", "farboo"];
var three = [13, 421];
var four = ["seven", "eight", "eleven"];
如何将它们合并到一个数组中并以最简单的方式返回?我得到的是
var result = [one,two,three,four];
导致
|-----------------------------|
| apple | banana | berry |
| foobar | barfoo | farboo |
| 13 | 421 | |
| seven | eight | eleven |
|-----------------------------|
但是,我真正需要的是:
|------------------------------------|
| apple | foobar | 13 | seven |
| banana | barfoo | 421 | eight |
| berry | farboo | | eleven |
|------------------------------------|
尝试
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);
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;
}