在 for 循环中将日期添加到日期 javascript

add days to a date in a for-loop 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,则最后一条日志应为:"The next day is: Monday 09. February...." 但是日志显示类似 22.April 的内容,它甚至更改了时区....

如果我只 运行 一次,结果是正确的(2 月 9 日)。 它只是在 foor 循环中不起作用。 (我是 javascript 的新手)

有人有想法吗? 提前致谢,来自德国的 Sebi

日期被定义为字符串而不是数字。如果将它们更改为数字,它应该可以工作:

var days= [1, 3, 4];

您传递的是字符串数组而不是整数,因此您实际上是在向日期添加字符串。有两种选择

更好的选择

传入整数数组而不是字符串数组

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);

});