0

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);

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

But wouldn't that then always give a date 2 days after today? Rather than 50 dates all two days apart?
and change the +2 to +(2*i)
@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.
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!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.