javascript:在 function() { } 中使用当前的 for 循环计数器值?
在一个网站上我想这样做:(简化)
myHandlers = new Array();
for(var i = 0; i < 7; i++) {
myHandlers.push(new Handler({
handlerName: 'myHandler'+i, // works, e.g. ->myHandler1, 2, 3 etc.
handlerFunc: function(bla) { /*...*/ alert(i); } // doesn't work,all return 7
}
}
我可以将计数器设置为我的处理程序的另一个属性(这将复制当前值)并在我的函数中使用它,但我想,还有一种方法可以实际复制这个值,不是吗?
on a website i want to do this: (simplified)
myHandlers = new Array();
for(var i = 0; i < 7; i++) {
myHandlers.push(new Handler({
handlerName: 'myHandler'+i, // works, e.g. ->myHandler1, 2, 3 etc.
handlerFunc: function(bla) { /*...*/ alert(i); } // doesn't work,all return 7
}
}
I could set the counter as another attribute of my Handler (which would copy the current value) and use it inside my function, but I guess, there is also a way to actually copy this value, no?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当handlerFunc被调用时,函数内的
i
引用for
循环的i
。但i
可能不再具有相同的值。使用闭包将
i
的当前值绑定到匿名函数的作用域中:这里使用了一个匿名函数
(function(i) { … })(i)
并立即打电话。该函数将for
循环的i
值绑定到本地i
。该i
然后独立于for
循环的i
。When handlerFunc is called, the
i
inside the function refers to thei
of thefor
loop. But thati
does probably not have the same value any more.Use a closure to bind the current value of
i
in the scope of an anonymous function:Here an anonymous function
(function(i) { … })(i)
is used and called immediately. This function binds the value ofi
of thefor
loop to the locali
. Thati
is then independent from thei
of thefor
loop.使用闭包绑定
i
以使值保持不变Use a closure to bind the
i
so the value stays intact在您的示例中,函数中的
i
与函数外部的i
是相同的变量。随着i
在循环中递增,它也在函数内递增。因此,如果在循环结束后调用这些函数,它们都会发出“7”警报。您需要创建一个具有适当范围的新变量并将
i
的值复制到其中。像这样的事情就会产生预期的效果。
In your example,
i
in the functions is the same variable asi
outside the functions. Asi
is incremented in the loop, so is it incremented within the functions. As a result, if the functions are called after the loop has finished, they will all alert "7".You need to create a new variable with appropriate scope and copy the value of
i
into it.Something like this would create the desired effect.