2013-07-07 90 views
1

有人可以看看這個用新鮮的眼睛。日期循環增量和增長變量(mootools)

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 

爲什麼沒有起始日期變量增長?

(如果需要提琴here

回答

1

的問題是,nstart_date都指向同一個對象。你需要通過創造新的Date對象克隆的日期,例如:

n = new Date(start_date); 

Updated demo

例子:

> 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) 
+0

爲什麼downvoted?我認爲這是公平的解釋... – Rikard

+0

@Rikard我得到了像在完全不同的問題連續3 downvotes,所以它可能與答案質量 – mishik

+0

@ mishik無關,感謝您的答案!在你建議'start_date = new Date(n);'的帖子上,'但是在你的小提琴中你有倒置的'var n = new Date(start_date);'。小提琴把我放在正確的軌道上,你的解釋讓我感到困惑:)。這是一個錯字錯誤嗎? – Sergio