1

有人可以用新鲜的眼光看看这个。

var start_date = Date.parse('2013-07-01');
var i_date = Date.parse('2013-07-5');

console.log(start_date + '---before loop ');

for (var n = start_date; n < i_date; n.increment()) {
    console.log(start_date + '---inside loop ');
}
console.log(start_date + '---after loop ');

此代码产生:

Mon Jul 01 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---before loop
Mon Jul 01 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Tue Jul 02 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Wed Jul 03 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Thu Jul 04 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---inside loop
Fri Jul 05 2013 00:00:00 GMT+0200 (W. Europe Daylight Time)---after loop  

为什么start_date 变量会增长?

(如果需要,请在此处提琴)

4

1 回答 1

1

问题是,n并且start_date指向同一个对象。您需要通过创建新Date对象来克隆日期,例如:

n = new Date(start_date);

更新了演示

例子:

> a = new Date()
Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
> b = a
Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
> c = new Date(a)
Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
// Do some stuff with "a"
> a
Sat Jun 29 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
> b
Sat Jun 29 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
> c
Sun Jul 07 2013 19:51:09 GMT+0600 (Ekaterinburg Standard Time)
于 2013-07-07T13:50:58.467 回答