簡體   English   中英

為什么此javascript日期數組不起作用?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM