简体   繁体   English

for循环中的数组与第二个for循环数组javascript合并

[英]array in for loop merge with second for loop array javascript

I have a problem merging 2 arrays in an for loop see code: 我在for循环中合并2个数组时遇到问题,请参见代码:

function count_days(tijden,datums ){

        var length = tijden.length;
        element = null;
        var similarities =0;
        var backup = [];
        var dateArray =[];

        for (var i = 0; i <length; i++) {
                element = tijden[i];
                tijden[i] = element;


            dateArray = getDates(new Date(tijden[i]['begin']), new Date(tijden[i]['eind']));


         }

The problem is that when the code is running i get one array for each loop. 问题是当代码运行时,我为每个循环获取一个数组。 I need to get one array with the data from all loops. 我需要从所有循环中获取一个数组。 I tryde concat but didnt get this to work 我试一下concat但没有让它起作用

It should be... 它应该是...

dateArray.push(
  getDates(new Date(tijden[i]['begin']), new Date(tijden[i]['eind']))
);

... or, if getDates method returns an array and you want dateArray to be flattened: ...,或者,如果getDates方法返回一个数组并且您希望将dateArray平:

Array.prototype.push.apply(dateArray,
  getDates(new Date(tijden[i]['begin']), 
           new Date(tijden[i]['eind']))
);

As it stands now, you just rewrite dateArray at each step of for loop. 现在,您只需在for循环的每个步骤中重写dateArray


A sidenote: this... 旁注:这个...

element = tijden[i];
tijden[i] = element;

... makes exactly zero sense: at least one of these lines (most probably the latter) is redundant. ...的意义完全为零:这些行中的至少一条(很可能是后者)是多余的。 Remove this - and code becomes easier to read: 删除它-代码变得更容易阅读:

var element, currDates;
for (var i = 0, i < length; i++) {
  element = tijden[i];
  currDates = getDates(new Date(element.begin), new Date(element.eind));
  Array.prototype.push.apply(dateArray, currDates);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM