admin管理员组文章数量:1387334
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.
本文标签: javascriptAdding dates to an array through a loopStack Overflow
版权声明:本文标题:javascript - Adding dates to an array through a loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744483027a2608281.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论