javascript:使用函数(){}中的当前for循环计数器值? [英] javascript: Using the current for-loop counter-value inside a function() { }?

查看:162
本文介绍了javascript:使用函数(){}中的当前for循环计数器值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网站上我想这样做:(简化)

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 引用 i c $ c> for 循环,但 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循环计数器值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆