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