最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding dates to an array through a loop - Stack Overflow

programmeradmin1浏览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 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
Add a ment  | 

2 Answers 2

Reset to default 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.

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.

发布评论

评论列表(0)

  1. 暂无评论