【问题标题】:JavaScript/GoogleMaps/Geocode - Variable being unset inside callback function within for loopJavaScript/GoogleMaps/Geocode - 在 for 循环内的回调函数中未设置变量
【发布时间】: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


    【解决方案1】:
    for (var i = 0; i < locations.length; i++) {
        geocoder.geocode({
            'address': locations[i] // Returns location as expected
        }, (function (i) {
    
    
    
            var location = locations[i];
            function getLoc()
            {
    
               return location;
    
            }
    
            return function(results, status){
            if (status == google.maps.GeocoderStatus.OK) {
                console.log(getLoc());
            }
            }(i))
        })
    }
    

    试试这个

    【讨论】:

    • 想添加一些关于 javascript 范围的信息? :P
    • @laconbass 像对象一样传递它,更新代码,现在的 alert(locObj) 输出是什么?
    • @laconbass 你知道我认为还有位置变量并且它覆盖了你的位置变量,那是因为它未定义,所以使用一个对象来传递数据,就像我上面的代码一样
    • @Rustam 上面的代码在var locObj.location = locations[i]; 给我一个“意外令牌”错误,不知道为什么会这样。
    • @Rustam 我不是 OP,只是建议你解释一下“为什么”会发生这种情况
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多