如何在函数外部使用全局变量

Sur*_*Ram 2 javascript variables scope global function

我无法在JavaScript中访问函数外部的变量.

JavaScript代码:

 var latitude;
 var longitude;
 function hello()
   {
   for(var i=0;i<con.length;i++)
   {
   geocoder.geocode( { 'address': con[i]}, function(results, status) 
   {

        if (status == google.maps.GeocoderStatus.OK)
        {
            latitude=results[0].geometry.location.lat();
            longitude = results[0].geometry.location.lng();
        });
         alert(latitude);    //here it works well
   }
   }
   alert(latitude);      //here i am getting error: undefined
Run Code Online (Sandbox Code Playgroud)

如何在函数外部使用变量?

Sha*_*lav 5

这是因为您尝试在从服务器获得结果之前输出变量(geocode是异步函数).这是错误的方式.您只能在地理编码功能中使用它们:

geocoder.geocode( { 'address': con[i]}, function(results, status)  {
    if (status == google.maps.GeocoderStatus.OK) {
        latitude=results[0].geometry.location.lat();
        longitude = results[0].geometry.location.lng();
    }
    <--- there
});
Run Code Online (Sandbox Code Playgroud)

或者你可以使用回调函数:

var latitude;
var longitude;

function showResults(latitude, longitude) {
    alert('latitude is '+latitude);
    alert('longitude is '+longitude);
}

function hello()
{
    for(var i=0;i<con.length;i++)
    {
        geocoder.geocode( { 'address': con[i]}, function(results, status)  {
            if (status == google.maps.GeocoderStatus.OK) {
                latitude=results[0].geometry.location.lat();
                longitude = results[0].geometry.location.lng();
            }
            alert(latitude);    //here it works well
            showResults(latitude, longitude);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

但它是一样的.

而且,看起来你的格式有些错误.我稍微更新了一下代码.现在括号)和}在正确的位置.如果我错了,请纠正我.

无论如何,最好格式化代码.我想你的括号约2分钟.你必须使用正确的格式.