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

标签 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.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 是异步函数)。这是错误的方式。您只能在地理编码功能中使用它们:

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);
        });
    }
}

但是是一样的。

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

无论如何,格式化代码是一个很好的做法。我思考了你的括号大约两分钟。您必须使用正确的格式。

关于javascript - 如何在函数外部使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23477738/

相关文章:

c++ - 在 C++ 中更改全局变量

Python:如何在每次调用时更新变量的值?

php - fatal error : Call to undefined function fetch_assoc() in php

javascript - Coffeescript 回调和函数

javascript - 通过 exec 将变量传递给 PhantomJS

java - 如果没有为 Windows 上的 Chrome 23 安装 java 插件,则 navigator.javaEnabled() 返回 true

Javascript:如何将数组中的单个元素传递给函数

javascript - 简单关卡,选择DOM中的元素,优化,创建方法函数

java - 将字符串解析为不同的变量类型

javascript - 如果 statusCode 不是 200,http 调用会返回什么类型的错误对象?