函数意外返回undefined

时间:2018-04-27 22:48:10

标签: javascript

早上好,

我在使用以下功能时遇到了一些麻烦。

function getLocation() {
  var geoLat;
  var geoLong;
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(geo) {
        geoLat = geo.coords.latitude;
        geoLong = geo.coords.longitude;
        console.log(geoLat);
      });
    } else {
      alert("Geolocation information is required for this app to function correctly");
      return false;
    };
  console.log(geoLat);
  return {
    lat: geoLat,
    long: geoLong
  };
};

if语句中的第一个console.log(geoLat)返回在其上方指定的正确纬度。当我尝试在最终geoLat之前再次引用return变量时,它现在是undefined。如果指定的变量在未分配或清除的情况下将其值重新更改为undefined,该怎么办?

我确定这只是我制作某种形式的语法错误。我学习JS并且不了解这一点。

感谢。

编辑:既然我已经让我的思绪被第四个异步功能所震撼,我已经改变它但仍然存在以下问题

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(geo) {
      var test = geo.coords.latitude;
      console.log(test);
      console.log(geo.coords.latitude);
      return test;
    });
  } else {
    alert("Geolocation information is required for this app to function correctly");
    return false;
  };
}; 

所以console.log(test)会像console.log(geo.coords.latitude)那样返回正确的坐标,但return test;仍然会返回udefined。我猜测result是否等待异步功能完成?

0 个答案:

没有答案
相关问题