Skip to content
Advertisement

for inside another for is executed just once

I have the following code to create all possible intervals between two dates:

var minStart = new Date(2019, 10, 1);
var maxStart = new Date(2019, 10, 3);
var minStop = new Date(2019, 10, 20);
var maxStop = new Date(2019, 10, 22);

for (var i = minStart; i <= maxStart; i.setDate(i.getDate() + 1)) {
  for (var v = minStop; v <= maxStop; v.setDate(v.getDate() + 1)) {
    console.log(moment(i).format('DD/MM') + ' - ' + moment(v).format('DD/MM'));
  }
}

I am expecting to get the following result:

01/11 - 20/11
01/11 - 21/11
01/11 - 22/11
02/11 - 20/11
02/11 - 21/11
02/11 - 22/11
03/11 - 20/11
03/11 - 21/11
03/11 - 22/11

but I am getting only:

>01/11 - 20/11
>01/11 - 21/11
>01/11 - 22/11

I debugged the code by putting more console.log() outputs and it turns out, that the inner loop is run only once. Any idea why this is happening?

Here is a quick JSFiddle (without the moment library that I am using only for formatting).

Advertisement

Answer

The problem is that you’re mutating the objects, at the end of the first outer loop, minStop will have the same date as maxStop. To address that, use something like this: var v = new Date(minStop)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement