简体   繁体   English

为什么此javascript日期数组不起作用?

[英]Why doesn't this javascript date array work?

I'm trying to populate an array with a list of dates. 我正在尝试用日期列表填充数组。

When I go back to retrieve a date in the array, they are all the same date. 当我返回检索数组中的日期时,它们都是相同的日期。

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
}

It's probably something stupid, but I'm at a loss. 这可能是愚蠢的,但我很茫然。

Thanks 谢谢

In your loop, you assign paydates[i] a reference to firstDate . 在循环中,您给paydates[i]引用firstDate At the end of 200 iterations, all 200 locations in the paydates array are pointing to the last firstDate . 在200次迭代结束时, paydates数组中的所有200个位置都指向最后一个firstDate

You should create a new Date instance in each iteration and then assign it to an index in the paydates array. 您应该在每次迭代中创建一个新的Date实例, 然后将其分配给paydates数组中的索引。

Also, you'll notice that the first date listed in your example is not 12/26/2010, but 1/9/2011. 此外,您会注意到示例中列出的第一个日期不是2010年12月26日,而是2011年9月9日。 I'm not sure if that's a mistake or intentional, but as your code is, the first firstDate isn't the date you used to seed your array of dates. 我不确定这是一个错误还是故意的,但是正如您的代码所示,第一个firstDate不是您用来firstDate日期数组的日期。

JSFiddle of a working example that also simplifies your code a little bit. JSFiddle是一个有效的示例,该示例还简化了您的代码。 Here is the barebones code from the fiddle: 这是小提琴的准系统代码:

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
}

Replace the first loop with: 将第一个循环替换为:

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 />");
}

The problem was that you were storing a reference to your one and only firstDate object to each index in your array. 问题在于您存储的是对数组中每个索引的一个且唯一的firstDate对象的引用。

You must create a new Date based on firstDate to get individual date to each element in array 您必须基于firstDate创建一个new Date以获取数组中每个元素的单独日期

Instead: 代替:

paydates[i] = firstDate;
firstDate.setDate(firstDate.getDate()+14); //add 14 days

write: 写:

paydates[i] = new Date( firstDate.setDate(firstDate.getDate()+14));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM