我有4个数组,我想将它们组合成1.我可以这样做,但我想从每个数组中取出一个元素,将其推送到我的新数组,然后获取接下来4等等。这就是我得到的:
var a = [ "foo", "bar", "baz", "bam", "bun", "fun" ];
var b = [ 1, 2, 3, 4, 5, 6];
var c=["a","b","c","d","e","f"];
var d=[7,8,9,10,11,12]
var neat=[];
neat= a.concat(b, c,d);
//neat=["foo","bar","baz","bam","bun","fun",1,2,3,4,5,6,"a","b","c","d","e","f",7,8,9,10,11, 12]
我想要的结果是这样的:
//neat=["foo",1,"a",7,"bar",2,"b",8...]
我不确定循环是否有效或是否需要使用其他功能
答案 0 :(得分:2)
假设每个源数组的长度相同:
a.forEach((e, i) => {
neat.push(e, b[i], c[i], d[i]);
};
答案 1 :(得分:1)
请尝试以下代码:
var a = [ "foo", "bar", "baz", "bam", "bun", "fun" ];
var b = [ 1, 2, 3, 4, 5, 6];
var c=["a","b","c","d","e","f"];
var d=[7,8,9,10,11,12]
var neat=[];
//neat= a.concat(b, c,d);
//neat=["foo","bar","baz","b
for (var i = 0; i < a.length ; i++)
{
neat.push(a[i], b[i], c[i], d[i]);
}
console.log(neat);
&#13;
答案 2 :(得分:1)
虽然Justins的回答是正确的,但是如果每次阵列的长度不一样,你可以做到
var maxItems = Math.max(a.length,b.length,c.length,d.length);
var neat = [];
for(var i = 0; i < maxItems; i++){
if(a[i] != undefined){
neat.push(a[i]);
}
if(b[i] != undefined){
neat.push(b[i]);
}
if(c[i] != undefined){
neat.push(c[i]);
}
if(d[i] != undefined){
neat.push(d[i]);
}
}
Math.max
会在4个数组之间找到最大数量的条目,然后在该数字上找到一个简单的for loop
,并在将其推送到{{1之前检查该值是否为undefined
}}
请参阅JSFiddle
答案 3 :(得分:-1)
因为所有数组的长度相等。所以我们可以使用循环轻松完成。
user1 11/11/2018 test