2015-02-09 118 views
1

我的問題是:在for循環中添加日期javascript

我想穿過一個數組,其中包含數字。 對於每個號碼,我想這個數字爲天添加一定 日期:

var days= ["1", "3", "4"]; 

$.each(days, function(key,value){ 

    var start = new Date(2015,01,08); 

    var nextDay = new Date(start); 

    console.log("start-day is:"+nextDay+ " and I should add "+value+" days"); 

    nextDay.setDate(start.getDate()+value); 

    console.log("The next day is:"+nextDay); 

}); 

的啓動日期是8號。二月。 如果值爲1,最後一個日誌應該是:「第二天是:星期一09. 2月....」 但日誌中寫着類似於22.April,它甚至改變了時區....

如果我只運行一次,結果是正確的(9月2日)。 它只是在foor循環中不起作用。 (我是javascript的新手)

有人有想法嗎? 在此先感謝,來自德國的Sebi

+0

對不起,第一行應該是:var days = [1,2,4]; – 2015-02-09 14:49:10

+0

請注意,您可以隨時編輯問題,但不要編輯它以添加解決方案:我們需要原始問題! – 2015-02-09 15:00:53

+0

您的版本後,代碼似乎是正確的:我看到「第二天是:星期四2015年2月12日00:00:00 GMT + 0100(浪漫標準時間)」 – 2015-02-09 15:05:37

回答

1

您正在傳遞字符串數組而不是整數,因此實際上是將字符串添加到日期。有兩個選項

更好的選擇

通行證在整數數組不是字符串數組

var days= [1,3,4]; // This is an array of integers 

$.each(days, function(key,value){ 

    var start = new Date(2015,01,08); 

    var nextDay = new Date(start); 

    console.log("start-day is:"+nextDay+ " and I should add "+value+" days"); 

    nextDay.setDate(start.getDate()+value); 

    console.log("The next day is:"+nextDay); 

}); 

更糟糕的選項

您可以parseInt()您的陣列或使數組編號就在您將其添加到開始日期之前。

var days= ["1", "3", "4"]; // These are strings not integers 

$.each(days, function(key,value){ 

    var start = new Date(2015,01,08); 

    var nextDay = new Date(start); 

    console.log("start-day is:"+nextDay+ " and I should add "+value+" days"); 

    nextDay.setDate(start.getDate()+parseInt(value)); // Strings are converted to integers here 

    console.log("The next day is:"+nextDay); 

}); 
1

日期被定義爲字符串而不是數字。如果將它們更改爲數字,它應該可以工作:

var days= [1, 3, 4];