你i
變量是當天顯示的號碼。您的firstDate
變量是Date
。
這條線:
var d = new Date(firstDate + i);
一起將這些並嘗試建立一個新的Date
。由於這些是不同的類型(一個日期和一個數字),類型強制就起作用了(即:日期和數字被轉換爲字符串,並連接在一起)。
試試這個:
var DAY_IN_MS = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var theDate = new Date("2017-04-10");
var i = 5;
// Date + Number = Type Coercion! Both objects will be converted to strings and concatenated together.
alert(theDate + i);
// The Date constructor doesn't care, and will work because it can get a date from the first part of the string.
alert(new Date(theDate + i));
// If you use `getTime()` you can get the numerical value of the Date, which you can use for arithmetic.
alert(theDate.getTime());
// By adding `i`, however, you are only adding a few milliseconds to the first date !!
alert(new Date(theDate.getTime() + i);
// Number + Number of days times milliseconds per day = success!
alert(new Date(theDate.getTime() + (i * DAY_IN_MS)));
我想你的意思:
var d = new Date(firstDate.getTime() + (i * Day));
請看看您的瀏覽器控制檯:它會在您的代碼中顯示語法錯誤和引用錯誤的詳細信息。修復這些代碼並且代碼將會運行,儘管你不應該有一個叫'Date'的變量,因爲已經有'Date'函數了,但是在顯示的代碼中你實際上並沒有對結果日期做任何事情 - 它們應該在哪裏被顯示? – nnnnnn
編輯我的代碼。但它顯示的第一個日期只有不增加日期 –
當有疑問發生了什麼,採取嬰兒的步驟。如果將'firstDate + i'分配給變量並檢查,在使用結果值創建新日期之前,解決問題的方法應該是微不足道的。 – migueldiab