1

I have a problem merging 2 arrays in an for loop see code:

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

4

1 回答 1

1

它应该是...

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

...或者,如果getDates方法返回一个数组并且您想要dateArray展平:

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

就目前而言,您只需在循环dateArray的每一步都重写。for


旁注:这...

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

... 完全零意义:这些行中至少有一条(很可能是后者)是多余的。删除它 - 代码变得更容易阅读:

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);
}
于 2013-11-13T11:22:09.020 回答