【问题标题】:Return undefined value in javascript function在javascript函数中返回未定义的值
【发布时间】:2014-04-01 05:57:44
【问题描述】:

我有以下代码:

js 加载:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

js函数:

<script type="text/javascript">

    var get_location;

    function get_google_latlng() {

        var geocoder =  new google.maps.Geocoder();
        geocoder.geocode( { 'address': 'iran'}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                window.get_location = results[0].geometry.location.lat();
            } else {
                window.get_location = status;
            }
        });

        return window.get_location;
    }

    var lat = get_google_latlng();

    alert(lat);
</script>

返回函数是undefined

window.get_location 命令也不起作用。

【问题讨论】:

  • 你想用window.get_location 达到什么目的?你认为它是/做什么?
  • 尝试使用 'get_location' 而不是 'window.get_location'
  • 使用警报('test');在条件中并尝试找出哪里出了问题
  • get_location 命令也不起作用。

标签: javascript function return undefined


【解决方案1】:

您遇到的是异步函数的问题。您没有立即获得 geocode 方法的值,因为您正在发出 ajax 请求并且这需要时间。典型的 JavaScript 新手。

回调和闭包是让您在编写 JavaScript 时更轻松的技术。我会建议你改变你的思维方式,这不再是涡轮帕斯卡了。这是 JavaScript。 异步。不要期望每个函数都立即返回结果。

回调示例:

// Ugly global variable
var get_location;

// Even more ugly global function
function get_google_latlng(callback) {

    var geocoder =  new google.maps.Geocoder();
    geocoder.geocode( { 'address': 'iran'}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            window.get_location = results[0].geometry.location.lat();
        } else {
            window.get_location = status;
        }

        // Now you invoke the callback to notify that the results are ready
        callback();
    });

    // This is absolutely unnecessary
    return window.get_location;
}

get_google_latlng(function(){

   // Only here we are sure the variable was actually written       
   alert(window.get_location);
});

最后一件事,永远不会在“window”(JavaScript 中的全局对象)下直接声明函数和变量,这是一种反模式,将来会让您头疼。

请学习如何制作匿名函数。

【讨论】:

  • 我想接收输出。
  • 你可以在回调中做任何你想做的事情。这就是你“接收”输出的地方。
【解决方案2】:

试试这个代码:

var get_location;
var geocoder =  new google.maps.Geocoder();
geocoder.geocode( { 'address': 'iran'}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            get_location = results[0].geometry.location.d;
            alert(get_location);
        }
});

您的代码的问题是,先执行警报,然后执行获取位置功能。

【讨论】:

  • 我想接收输出。我不想提醒。
猜你喜欢
  • 1970-01-01
  • 2016-05-20
  • 1970-01-01
  • 2021-03-17
  • 2013-07-01
  • 2019-01-07
  • 1970-01-01
  • 2014-02-03
  • 1970-01-01
相关资源
最近更新 更多