Search code examples
javascriptmootools

date loop increment and growing variable ( mootools )


Can someone please take a look at this with fresh eyes.

var start_date = Date.parse('2013-07-01');
var i_date = Date.parse('2013-07-5');

console.log(start_date + '---before loop ');

for (var n = start_date; n < i_date; n.increment()) {
    console.log(start_date + '---inside loop ');
}
console.log(start_date + '---after loop ');

This code produces this:

Mon Jul 01 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---before loop
Mon Jul 01 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Tue Jul 02 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Wed Jul 03 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Thu Jul 04 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Fri Jul 05 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---after loop  

Why does start_date variable grow?

(fiddle here if needed)


Solution

  • The problem is that n and start_date are pointing to the same object. You need to clone the date by creating new Date object, for example:

    n = new Date(start_date);
    

    Updated demo.

    Example:

    > a = new Date()
    Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
    > b = a
    Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
    > c = new Date(a)
    Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
    // Do some stuff with "a"
    > a
    Sat Jun 29 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
    > b
    Sat Jun 29 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
    > c
    Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)