所以我的基本设置是这样的:
for (var i = 0; i < 3; i++) {
var indices = [-1, -1, -1];
while (index == -1) {
// Do Stuff
index[i] = newIndex;
}
var press = function() { alert(i); };
new control({press: press});
}
现在,当我按下每个新控件而不是收到警报(0)、警报(1)和警报(2)时,我收到警报(3)、警报(3)和警报(3)。 我能理解发生了什么事。现在我的问题:如何按照我的预期将不同的索引传递给函数?
最佳答案
这是因为闭包变量i
,解决方案是为每个循环创建一个私有(private)闭包。
for (var i = 0; i < 3; i++) {
var indices = [-1, -1, -1];
while (index == -1) {
// Do Stuff
index[i] = newIndex;
}
var press = (function(myvar){
return function() { alert(myvar); };
})(i);
new control({press: press});
}
关于Javascript 向内部函数提供参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17062121/