问题描述
在我想这样做的网站上:(简化)
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
}
}
我可以将计数器设置为我的 Handler 的另一个属性(它将复制当前值)并在我的函数中使用它,但我想,还有一种方法可以实际复制这个值,不是吗?
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?
推荐答案
当调用handlerFunc时,函数内部的i指的是ifor 循环的代码>.但是那个 i 可能不再具有相同的值了.
When handlerFunc is called, the i inside the function refers to the i of the for loop. But that i does probably not have the same value any more.
使用闭包将 i 的当前值绑定到匿名函数的范围内:
Use a closure to bind the current value of i in the scope of an anonymous function:
handlerFunc: (function(i) { return function(bla) { /*...*/ alert(i); }; })(i)
这里使用了一个匿名函数 (function(i) { … })(i) 并立即调用.该函数将 for 循环的 i 的值绑定到本地 i.该 i 然后独立于 for 循环的 i.
Here an anonymous function (function(i) { … })(i) is used and called immediately. This function binds the value of i of the for loop to the local i. That i is then independent from the i of the for loop.
这篇关于javascript:在函数(){}中使用当前的for循环计数器值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)