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

Javascript 如何在函数外部使用全局变量,javascript,function,variables,scope,global,Javascript,Function,Variables,Scope,Global,在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.Geoco

在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
var纬度;
var经度;
函数hello()
{

对于(var i=0;i这是因为您试图在从服务器获得结果之前输出变量(
geocode
是异步函数)。这是错误的方法。您只能在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
});
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);
        });
    }
}
geocoder.geocode({'address':con[i]},函数(结果,状态){
if(status==google.maps.GeocoderStatus.OK){
纬度=结果[0]。几何体。位置。纬度();
经度=结果[0]。几何体。位置。lng();
}

geocode
是一个异步函数-您需要使用回调实际上,您可以访问
latitude,longitude
变量,它们只是在您的
hello
函数退出时尚未设置感谢u@sharikov…我想在函数hello()和showResults()之外使用latitude和longitude变量作为一个字符串,您可以帮助我如何获取函数之外的纬度和经度值。正如我所说的,您只能使用其中一种方法。请尝试在那里找到文章:如何获取Ajax响应