【问题标题】:Returning values in Javascript在 Javascript 中返回值
【发布时间】:2011-04-05 17:09:24
【问题描述】:

我有一个(希望很简单)Javascript 问题。我进行了搜索,但没有找到与问题真正相关的内容。

基本上,我有一个函数 (addToGlobe),它在运行时会调用另外两个函数(codeAddressLat 和 codeAddressLng)。两个被调用的函数都应该向第一个函数返回一个浮点值,然后第一个函数使用它们。子函数肯定能正常工作——我做了一个打印语句来检查每个子函数中的“numfinal”变量是否有一个值,而且确实如此。

但是,当我将打印语句添加到调用函数时(如代码中所述),它返回“未定义”。因此,问题似乎出在返回 numfinal 值的时候。

谢谢:)

function addToGlobe(uname, uid, pmcity) {
    // Get lat & long of city
    var pmlat = codeAddressLat(pmcity);
    var pmlong = codeAddressLng(pmcity);

    log(pmlat);   // PROBLEM! Prints 'undefined'
    log(pmlong);  // PROBLEM! Prints 'undefined'

    // Rest of function removed to keep it simple
}

function codeAddressLat(inputcity) {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);

    geocoder.geocode( { 'address': inputcity}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
          var llsplit = new Array();

          bkresult = String(results[0].geometry.location);
          bkresult = bkresult.replace(/[\(\)]/g, "");
          llsplit = bkresult.split(',');

          numfinal = parseFloat(llsplit[0]);
          return numfinal;

      } else {
        log('<b><font color="#C40031">Geocode was not successful:</b> ' + status);
      }
    });
 }

  function codeAddressLng(inputcity) {
        // Basically the same function as above. Removed for simplicity
     }

【问题讨论】:

    标签: javascript variables return


    【解决方案1】:

    codeAddressLat 实际上并没有返回任何东西。它传递给geocoder.geocode 的匿名函数是。

    由于 geocoder.geocode 是异步运行的,codeAddressLat 不能等待它的回答。所以 codeAddressLat 真的不能返回任何有价值的东西。相反,codeAddressLat 也需要变得异步。这是 JavaScript 中的常见模式。

    function addToGlobe(uname, uid, pmcity) {
         codeAddressLat(pmcity, function(pmlat) {
            // do something with pmlat
        });
    
        ...
    }
    
    function codeAddressLat(inputcity, callback) {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(-34.397, 150.644);
    
        geocoder.geocode( { 'address': inputcity}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              var llsplit = new Array();
    
              bkresult = String(results[0].geometry.location);
              bkresult = bkresult.replace(/[\(\)]/g, "");
              llsplit = bkresult.split(',');
    
              numfinal = parseFloat(llsplit[0]);
    
              // instead of returning, call the callback with the result
              callback(numfinal);
    
          } else {
            log('<b><font color="#C40031">Geocode was not successful:</b> ' + status);
          }
        });
    }
    

    【讨论】:

      【解决方案2】:

      codeAddressLat 中没有 return 语句,但在 codeAddressLat 中定义的回调函数中有一个。

      【讨论】:

        【解决方案3】:

        您的函数codeAddressLat 实际上并没有返回一个值,而是调用您传递一个返回值的回调函数的函数。您需要等到地理编码操作完成才能检索 numfinal 的值。

        【讨论】:

          【解决方案4】:

          您的函数 codeAddressLat 根本没有返回任何值,因此您的输出未定义。

          【讨论】:

          • codeAddressLat 根本没有返回任何东西(这意味着它默认返回未定义)。 return 语句不在 codeAddressLat 本身中。
          • @Matt - 是的,你是对的。错过了看到封闭的功能。谢谢
          【解决方案5】:

          codeAddressLat 方法调用中的地理编码请求,不会将值返回给调用者。您的退货范围不同。

          【讨论】:

            【解决方案6】:

            这行得通吗?

            function codeAddressLat(inputcity) {
                geocoder = new google.maps.Geocoder();
                var latlng = new google.maps.LatLng(-34.397, 150.644);
            
                return geocoder.geocode( { 'address': inputcity}, function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                      var llsplit = new Array();
            
                      bkresult = String(results[0].geometry.location);
                      bkresult = bkresult.replace(/[\(\)]/g, "");
                      llsplit = bkresult.split(',');
            
                      numfinal = parseFloat(llsplit[0]);
                      return numfinal;
            
                  } else {
                    log('<b><font color="#C40031">Geocode was not successful:</b> ' + status);
                  }
                });
             }
            

            【讨论】:

              【解决方案7】:

              geocoder.geocode 函数看起来是异步的。在 geocoder.geocode 函数从服务器取回数据之前,您的 codeAddressLatcodeAddressLng 函数返回 void。

              解决此问题的一种方法是将您的调用嵌套到 geocoder.geocode 并使用变量范围,这样当所有 AJAX 调用都返回时,您可以调用您的 addToGlobe 函数并传递您想要的两个参数。

              类似这样的:

              codeAddressLatAndLong(pmcity);
              
              function addToGlobe(pmlatlat, pmlatlong) {
                  log(pmlat);   // PROBLEM! Prints 'undefined'
                  log(pmlong);  // PROBLEM! Prints 'undefined'
              
                  // Rest of function removed to keep it simple
              }
              
              function codeAddressLatAndLong(inputcity) {
                  // stuff
              
                  geocoder.geocode( { 'address': inputcity}, function(results, status) {
                    // stuff goes here
                    pmlat = parseFloat(llsplit[0]);
                    geocoder.geocode({...}, function(results, status) {
                       // more stuff
                       pmlatlong = something;
                       addToGlobe(pmlatlat, pmlatlong);
                    });
                  });
              }
              

              欢迎来到 AJAX 的世界。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2021-07-05
                • 1970-01-01
                相关资源
                最近更新 更多