5

我想在循环运行时向 Google geocoder API 调用添加一些额外的参数,但我不确定如何将闭包参数附加到它们的匿名函数中,该函数已经具有通过调用传入的默认参数API。

例如:

for(var i = 0; i < 5; i++) {
     geocoder.geocode({'address': address}, function(results, status) {
         // Geocoder stuff here
     });
}

我希望能够在传递的 geocoder.geocode() 匿名函数中使用 i 的值,但是如果我}(i));在第 4 行使用了一个闭包,那么它将替换第一个会破坏地理编码器的参数。

有没有办法可以使用闭包,或者将 i 的值传递给匿名函数?

实际上我想做的是:

geocoder.geocode({'address': address}, function(results, status, i) {
    alert(i); // 0, 1, 2, 3, 4
}(i));

但工作:-)

4

2 回答 2

11

您可以i直接从匿名函数访问(通过闭包),但您需要捕获它,以便每次调用都geocode获得自己的副本。像往常一样在 javascript 中,添加另一个函数就可以了。我重命名了外部i变量以使其更清晰:

for(var iter = 0; iter < 5; iter++) {
    (function(i) {
        geocoder.geocode({'address': address}, function(results, status) {
            // Geocoder stuff here
            // you can freely access i here
        });
    })(iter);
}
于 2010-10-20T14:27:48.917 回答
3
function geoOuter(i) {
    geocoder.geocode({'address': address}, function(results, status) {
         // Geocoder stuff here
         // This has access to i in the outer function, which will be bound to
         // a different value of i for each iteration of the loop
     });
}

for(var i = 0; i < 5; i++) {
    geoOuter(i);
}

Oughta do it...

于 2010-10-20T14:26:24.830 回答