【发布时间】:2014-05-20 18:14:36
【问题描述】:
我已经在 SE 上搜索了 2 个小时,现在试图解决我失去“位置”变量值的原因。利用闭包看起来是最好的解决方案,但在下面的回调函数的上下文中,我无法弄清楚如何正确实现它。
有人可以就这种现象提供一点见解,如何才能纠正它?如果有任何关键术语,请指出,以便我进行相应的研究。
感谢您的宝贵时间。
有问题的代码:
for (var i = 0; i < locations.length; i++) {
geocoder.geocode({
'address': locations[i] // Returns location as expected
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(locations[i]); // returns undefined
}
})
}
为了澄清,我已经看到了与此类似的最接近的帖子:When using callbacks inside a loop in javascript, is there any way to save a variable that's updated in the loop for use in the callback?,但我无法使其在这种情况下工作。
再次感谢。
【问题讨论】:
标签: javascript for-loop closures google-geocoder