I am going through a for loop, adding a time onto the current date, and adding the new date into an array. However, when I output the array once the loop is completed, it is filled with 50 instances of the same date. Logging these dates from within the loop however shows them being incremented correctly. Is this something to do with the data being updated after it has already been pushed into the array?

var dates = new Array();
var currentDate = new Date();
for (var i =0; i < 50;i++){
    currentDate.setDate(currentDate.getDate()+2);
    console.log(currentDate);
    dates.push(currentDate);
}
console.log(dates);
share|improve this question

2 Answers

up vote 4 down vote accepted

Move var currentDate = new Date(); inside for loop. Otherwise you are modifying the same object and adding 50 references of it in the array.

In the end you see the the same object printed 50 times with the last updated date value.

share|improve this answer
But wouldn't that then always give a date 2 days after today? Rather than 50 dates all two days apart? – glenn sayers Nov 9 '12 at 2:41
1  
and change the +2 to +(2*i) – Eli Gassert Nov 9 '12 at 2:41
@glennsayers: What date are you getting? I think you would be getting all 50 object with same date as 100 days after today i.e. Feb 16, 2013. – Yogendra Singh Nov 9 '12 at 2:50
Correct, I am. So it it's putting the same object into the array 50 times, so when I update one object,they all get updated? I get it now. Thanks! – glenn sayers Nov 9 '12 at 3:03

You can do as Yogendra suggests, or change:

> dates.push(currentDate);

to

dates.push(new Date(currentDate));

to get a different date object for each member of the array.

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.