This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                                
                                    (6个答案)
                                
                        
                                2年前关闭。
            
                    
我正在尝试覆盖一个变量,但是不知何故它不起作用。
我在这里做错了什么?

    var url = 'BB';

    navigator.geolocation.getCurrentPosition(function (position) {
        url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude.toString() + ',' + position.coords.longitude.toString();
    });

    console.log(url);


我的url是否应该获取整个字符串而不是输出bb

最佳答案

这是因为navigator.geolocation.getCurrentPosition是异步的,并且console.log(url)在覆盖URL的回调函数之前执行

如果您不熟悉asynchronous执行,此线程可能会有所帮助:

Asynchronous vs synchronous execution, what does it really mean?

10-07 19:38