Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS如何连接数组中的数组_Javascript_Arrays_Concat - Fatal编程技术网

Javascript JS如何连接数组中的数组

Javascript JS如何连接数组中的数组,javascript,arrays,concat,Javascript,Arrays,Concat,更具体地说,有没有更简单的方法: var test0 = [[0,2,4], [1,3,5]]; var test1 = [[6,8], [7,9,11]]; test0.forEach( function(item0, index) { test1[index].forEach( function(item1) { item0.push(item1); } ); }

更具体地说,有没有更简单的方法:

var test0 = [[0,2,4], [1,3,5]];
var test1 = [[6,8], [7,9,11]];

test0.forEach(
    function(item0, index) {
        test1[index].forEach(
            function(item1) {
                item0.push(item1);
            }
        );
    }
);
我曾尝试在
forEach()
的第一级使用
concat()
,但由于我仍然无法理解的原因,它不起作用

编辑: 谢谢你的第一个答案。 奖金问题,为什么这个不起作用

var test0 = [[0,2,4], [1,3,5]];
var test1 = [[6,8], [7,9,11]];

test0.forEach(
    function(item, index) {
        item.concat(test1[index]);
    }
);

提前感谢

一个选项是使用
.map
并展开两个数组,从另一个较大数组中的适当索引中获取第二个内部数组:

var test0=[[0,2,4],[1,3,5];
var test1=[[6,8],[7,9,11];
log(test0.map((arr,i)=>[…arr,…test1[i]])使用和

var test0=[[0,2,4],[1,3,5];
var test1=[[6,8],[7,9,11];
test0=test0.map((a,i)=>[…a,…test1[i]]);
log(test0)

基准:

让test0=[[0,2,4],[1,3,5];
设test1=[[6,8],[7,9,11];
让结果=[]
for(设i=0;iconsole.log(result)
任意数组计数的解决方案

var test0=[[0,2,4],[1,3,5],
test1=[[6,8],[7,9,11]],
result=[test0,test1].reduce((a,b)=>a.map((v,i)=>[…v,…b[i]]))

控制台日志(结果)
concat
将生成一个新数组,而不是修改当前数组。因此,为了使其工作,您需要将新生成的数组分配回同一索引上的父数组

var test0=[[0,2,4],[1,3,5];
var test1=[[6,8],[7,9,11];
test0.forEach(
功能(项目、索引){
test0[索引]=item.concat(test1[索引]);
}
);

log(test0)上面的示例给出了预期结果。应该是[[0,2,4,6,8],[1,3,5,7,9,11]。我建议您在此处使用lodash或下划线。第二句包含您奖金问题的答案。(请注意,仅分配给
项是不够的,但您必须将结果分配给
test0[index]
)@barbsan谢谢!)您的方法与CertainPerformance的答案非常相似。我猜他比你快了一分钟-p@Rajesh-是的。我花了一些额外的时间来获取链接:p,显然,CertainPerformance更快地理解了这个问题。尽管您试图使用JSPerf链接描述的内容是正确的,但请尽量保持操作的相似性。检查:谢谢,更改了答案看起来你是reduce函数的忠实粉丝。