【发布时间】: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