我在日期里面循环。下面的代码片段是我到目前为止所做的代码示例。它工作正常,除了循环开始。
var from = new Date(2015, 0, 1);
var to = new Date(2015, 0, 10);
while(from < to) {
from = new Date(from.setDate(from.getDate()+1));
console.log(from.getDate());
}
//output: 2, 3, 4, 5, 6, 7, 8, 9, 10
正如您所看到的,循环从数字2
开始。我希望它从1
开始,因为我声明的日期是var from = new Date(2015, 0, 1);
。我希望输出为1, 2, 3, 4, 5, 6, 7, 8, 9, 10
。我的代码怎么了?为什么它从2
开始?
答案 0 :(得分:0)
尝试使用此var from = new Date(2015, 0, 0);
替换第一行您在记录日期之前递增日期,这意味着从1开始时记录的第一个值为2
答案 1 :(得分:0)
您需要在递增之前使用该值
var from = new Date(2015, 0, 1);
var to = new Date(2015, 0, 10);
while (from <= to) {
console.log(from.getDate());
//this should be last in the loop
//from = new Date(from.setDate(from.getDate() + 1));
from.setDate(from.getDate() + 1)
}
演示:Fiddle