[英]Why doesn't this javascript date array work?
我正在尝试用日期列表填充数组。
当我返回检索数组中的日期时,它们都是相同的日期。
var paydates = new Array();
var i;
var firstDate = new Date();
firstDate.setFullYear(2010, 11, 26); //set the first day in our array as 12/26/10
for (i=0; i < 200; i++) //put 200 dates in our array
{
paydates[i] = firstDate;
firstDate.setDate(firstDate.getDate()+14); //add 14 days
document.write("1st: " + i + ":" + paydates[i] + "<br />");
//this lists the dates correctly
}
//when I go back to retrieve them:
for (i=0; i < 200; i++)
{
document.write("2nd: " + i + ":" + paydates[i] + "<br />");
//this lists 200 instances of the same date
}
这可能是愚蠢的,但我很茫然。
谢谢
在循环中,您给paydates[i]
引用firstDate
。 在200次迭代结束时, paydates
数组中的所有200个位置都指向最后一个firstDate
。
您应该在每次迭代中创建一个新的Date
实例, 然后将其分配给paydates
数组中的索引。
此外,您会注意到示例中列出的第一个日期不是2010年12月26日,而是2011年9月9日。 我不确定这是一个错误还是故意的,但是正如您的代码所示,第一个firstDate
不是您用来firstDate
日期数组的日期。
JSFiddle是一个有效的示例,该示例还简化了您的代码。 这是小提琴的准系统代码:
var paydates = []; // new array
var firstDate = new Date(2010, 11, 26); // seed date
for (var i = 0; i < 200; i++) {
paydates.push(new Date(firstDate.getTime()));
firstDate.setDate(firstDate.getDate() + 14); // add 14 days
}
将第一个循环替换为:
var temp;
for (i=0; i < 200; i++) //put 200 dates in our array
{
temp = new Date(firstDate.getTime());
paydates[i] = temp;
firstDate.setDate(firstDate.getDate()+14); //add 14 days
document.write("1st: " + i + ":" + paydates[i] + "<br />");
}
问题在于您存储的是对数组中每个索引的一个且唯一的firstDate对象的引用。
您必须基于firstDate创建一个new Date
以获取数组中每个元素的单独日期
代替:
paydates[i] = firstDate;
firstDate.setDate(firstDate.getDate()+14); //add 14 days
写:
paydates[i] = new Date( firstDate.setDate(firstDate.getDate()+14));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.