【问题标题】:How to use global variables in outside of function如何在函数外部使用全局变量
【发布时间】:2014-05-05 16:49:38
【问题描述】:

我无法在 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

如何在函数外使用变量?

【问题讨论】:

  • geocode 是一个异步函数 - 你需要使用回调
  • 其实你可以访问latitude,longitude变量,只是在你的hello函数退出时它们还没有被设置

标签: javascript function variables scope global


【解决方案1】:

这是因为您尝试在从服务器获取结果之前输出变量(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);
        });
    }
}

但它是一样的。

此外,您的格式似乎有些错误。我更新了一点代码。现在括号 ) 和 } 在正确的位置。如果我错了,请纠正我。

无论如何,格式化代码是一个好习惯。我在考虑你的括号大约 2 分钟。您必须使用正确的格式。

【讨论】:

  • 谢谢@sharikov ...我想在函数 hello() 和 showResults() 之外使用纬度和经度变量作为字符串你能帮我如何在函数之外获取纬度和经度值.
  • 正如我所说,您只能使用其中一种方法。尝试在那里找到帖子:如何获得 Ajax 响应
猜你喜欢
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多