循环中的javascript闭包 [英] javascript closure in loop
问题描述
var a = [],i = 0,j = 0; (c){
a.push(function())
(i = 0; i <5; i + = 1){
{
console.log(c);});
})(i);
}; (j = 0; j <5; j + = 1){a [j]();为什么 i
总是会变大1而不是停留 5
?没有foor循环已经被传递,所以赋给匿名函数的 i
参数应该是 5
?解决方案 如果您从内部闭包引用 i
在所有情况下看到的结果是5。但是,您可以将 i
由值传递给外部函数,该函数被接受为参数 c
。然后,在创建内部闭包的时刻,将 c
的值固定为任何 i
为 / b>
考虑更改日志语句:
console。日志(c:+ c +i:+ i);
您应该看到 c
从0到4(含)以及 i
在所有情况下均为5元。
Following code is given:
var a = [ ], i = 0, j = 0;
for (i = 0; i < 5; i += 1) {
(function(c) {
a.push(function () {
console.log(c); });
})(i);
};
for (j = 0; j < 5; j += 1) { a[j](); }
Why does i
always get bigger by 1 instead of staying 5
? Hasn't the foor loop already been passed, so the i
parameter given to the anonymous function should be 5
?
解决方案 If you referenced i
from the inner closure then yes, you would see the result being 5 in all cases. However, you pass i
by value to the outer function, which is accepted as parameter c
. The value of c
is then fixed to whatever i
was at the moment you created the inner closure.
Consider changing the log statement:
console.log("c:" + c + " i:" + i);
You should see c
going from 0 to 4 (inclusive) and i
being 5 in all cases.
这篇关于循环中的javascript闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文