2010-10-28 21 views
2

可能顯示的文件:
Javascript closure inside loops - simple practical example
Javascript closure 「stores」 value at the wrong time如何計數到3?

for (var i = 1; i <= 3; ++i) { 
    setTimeout(function() { 
     alert(i); 
    }, i * 1000); 
} 

這提醒 「4」 的3倍。我知道爲什麼,但我不會在這裏糟...它,儘管我忘了如何解決它。解決這個問題的簡明方法是什麼?

+0

究竟是什麼問題,你試圖解決? – 2010-10-28 01:57:15

+2

[Javascript閉包內部循環 - 簡單實用示例]的可能重複(http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example)和幾乎所有[javascript + loops封+](http://stackoverflow.com/questions/tagged/javascript+loops+closures)。 – 2010-10-28 01:57:44

+0

zuckerberg,我看到了你的電影 – vol7ron 2010-10-28 02:02:35

回答

5
for (var i = 1; i <= 3; ++i) { 
    setTimeout((function (x) { 
     return function() { alert(x); } 
    })(i), i * 1000); 
} 
+1

@rchern我不介意,但這已被解釋[千倍](http://stackoverflow.com/questions/tagged/javascript+loops+closures)已經和這個問題似乎註定要快速關閉(雙關語打算)作爲其中一個副本。另外,OP似乎理解這個問題,他只是在尋找語法。 – deceze 2010-10-28 02:01:23

+0

@rchern爲什麼不呢?比沒有答案好半個答案? *聳肩* :) – deceze 2010-10-28 02:09:06

+0

@deceze:但一個完整的答案仍然比一半的答案更好。 – BrunoLM 2010-10-28 02:10:09

4

這是一個非常普遍的問題。 With JS 1.7 this is easily solved using let keyword。檢查browser version equivalency click here

您可以使用閉包解決此問題。爲i創建一個範圍並返回setTimeout的功能。

for (var i = 1; i <= 3; ++i) { 
    setTimeout((function(i) { /* i is now a parameter */ 
     return function() { /* this function is the one that will execute */ 
      alert(i); /* this `i` is not the same as the one used on the loop */ 
     } 
    })(i), i * 1000); 
}