简体   繁体   English

如何在闭包中访问全局变量? (JavaScript)的

[英]How to access a global variable in a closure? (Javascript)

            var events = <?php echo $sf_data->getRaw('jsonData'); ?>;//some perfecly fine json
            var locations = new Array();
            var geocoder = new google.maps.Geocoder();
            $(events).each(function(i,e){
                geocoder.geocode({address: e.place},function(results,statusCode){
                    locations[e.id] = results[0].geometry.location;
                })
            })
            alert(locations.length);

Okay, the question is easy. 好的,问题很简单。 How do i modify the locations array inside of closure? 如何修改闭包内的位置数组? The alert shows 0 . 警报显示0

The alert shows 0 because you modify locations asynchronously. 警报显示0,因为您异步修改locations Anonymous function where you modify locations will be called later then you show alert. 您修改locations匿名函数将在稍后调用,然后显示警报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM