如何在循环中的回调中引用`i`的正确值? [英] How to reference right value of `i` in a callback in a loop?
问题描述
我有这段代码:
for (var i = 0; i < result.length; i++) {
// call a function that open a new "thread"
myObject.geocode({ param1: "param" }, function(results, status) {
alert(result.title[i]);
});
}
.geocode
功能(不是我的,所以我无法编辑)打开一个新的执行线程。
The .geocode
function (that is not mine, so I can't edit) open a new "thread" of execution.
当我尝试在每一步上打印标题时,我总是得到 i
的最后一个可能值。
When I try to print title on each step, I get always the last possible value of i
.
如何为每次迭代保留对 i
的正确值的引用?
How can I keep a reference to the right value of i
for each iteration?
推荐答案
你可以在循环中创建一个闭包;
You can create a closure within the loop;
for (var i = 0; i < result.length; i++) {
// call a function that open a new "thread"
(function (i) {
myObject.geocode({ param1: "param" }, function(results, status) {
alert(result.title[i]);
});
}(i));
}
所以我们在这里创建一个函数;
So here we're creating a function;
(function (i) {
myObject.geocode({ param1: "param" }, function(results, status) {
alert(result.title[i]);
});
});
...接受一个名为的参数i
,并启动地理编码请求。通过在函数表达式声明的末尾添加(i)
,我们立即运行该函数并将其传递给 i的当前值
。
... which accepts one parameter named i
, and launches the geocode request. By adding the (i)
to the end of the declaration of a function expression, we run the function straight away and pass it the current value of i
.
(function (i) {
myObject.geocode({ param1: "param" }, function(results, status) {
alert(result.title[i]);
});
}(i));
变量 i
已经存在于比闭包更高的范围,因为 i
的本地声明会覆盖它。我们将传递给闭包的变量,或者闭包调用变量的名称可能不同;
It doesn't matter that a variable i
already exists at a higher scope than the closure, because the local declaration of i
overrides it. Either the variable we pass to the closure, or the name the closure calls the variable could be different;
(function (anotherVariable) {
myObject.geocode({ param1: "param" }, function(results, status) {
alert(result.title[anotherVariable]);
});
}(aVariable));
另外你也可以将逻辑提取到另一个函数(我更喜欢它) ,但它不那么很酷):
Alternately you could also extract the logic to another function (I prefer it, but it's less cool):
function geocode(i) {
myObject.geocode({ param1: "param" }, function(results, status) {
alert(result.title[i]);
});
}
for (var i = 0; i < result.length; i++) {
geocode(i);
}
问题在于相同 i
回调函数使用的变量;正如您所发现的那样,在回调执行时已经移动了。上述两种解决方案都为每次迭代创建了另一个变量,这就是回调操作。
The problem is down to the same i
variable being used by the callback functions; which, as you've discovered, has moved on by the time the callback executes. Both of the above solutions creates another variable for each iteration, and it is this that the callback operates on.
这篇关于如何在循环中的回调中引用`i`的正确值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!