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 pleted, 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);
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 pleted, 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
asked Nov 9, 2012 at 2:38
glenn sayersglenn sayers
2,4142 gold badges18 silver badges18 bronze badges
2 Answers
Reset to default 4Move 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.
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.