在for循环中添加日期javascript
问题描述:
我的问题是:在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
答
您正在传递字符串数组而不是整数,因此实际上是将字符串添加到日期。有两个选项
更好的选择
通行证在整数数组不是字符串数组
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);
});
答
日期被定义为字符串而不是数字。如果将它们更改为数字,它应该可以工作:
var days= [1, 3, 4];
对不起,第一行应该是:var days = [1,2,4]; – 2015-02-09 14:49:10
请注意,您可以随时编辑问题,但不要编辑它以添加解决方案:我们需要原始问题! – 2015-02-09 15:00:53
您的版本后,代码似乎是正确的:我看到“第二天是:星期四2015年2月12日00:00:00 GMT + 0100(浪漫标准时间)” – 2015-02-09 15:05:37