Javascript for date loop

I try to iterate every day after a month, but the for loop loops (in infinite mode):

var today = new Date();
var numberOfDaysInMonth = new Date( today.getFullYear(), lastMonth, 0 ).getDate();

...

for ( var date = new Date( today.getFullYear(), lastMonth, 1 ); date.getDate() <= numberOfDaysInMonth; date.setDate( date.getDate()+1 ) ) {

...

All parts of the for-loop arguments work as expected. If I replaced "<=" with only "<", on condition that the loop also works, but of course stops too early.

Does anyone have any ideas what could bring this cycle to infinity? I dont know...

+4
source share
2 answers
date.setDate( date.getDate()+1 )

When date.setDate (31 + 1) is called, the day reset is 0, and the month advances to 1 because it is the “next” date.

Instead, do this:

var begin = new Date("4 februari 2014");
var end = new Date("4 march 2014");

for (;begin < end; begin.setDate(begin.getDate()+1)) {
    console.log(begin);
}

4 februari 4 .

+1

setDate . getDate().

+3

Source: https://habr.com/ru/post/1527613/


All Articles