首页 文章

如何在函数内部的javascript函数之外返回一个变量?

提问于
浏览
2

所以我有

function find_coord(lat, lng) {
              var smart_loc;
      var latlng = new google.maps.LatLng(lat, lng);
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'latLng': latlng }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                smart_loc = new smart_loc_obj(results);
            } else {
                smart_loc = null;
            }
        });

        return smart_loc;
}

我想返回smart_loc变量/对象,但它总是为null,因为函数的范围(结果,状态)没有达到find_coord函数中声明的smart_loc . 那么如何在函数(结果,状态)中得到一个变量呢?

1 回答

  • 0

    你可以做:

    var smart_loc;
    
    function find_coord(lat, lng) {
      var latlng = new google.maps.LatLng(lat, lng);
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'latLng': latlng }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                smart_loc = new smart_loc_obj(results);
            } else {
                smart_loc = null;
            }
        });
    }
    

    或者,如果您需要在smart_loc更改时运行函数:

    function find_coord(lat, lng, cb) {
              var smart_loc;
      var latlng = new google.maps.LatLng(lat, lng);
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'latLng': latlng }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                smart_loc = new smart_loc_obj(results);
            } else {
                smart_loc = null;
            }
    
            cb(smart_loc);
        });
    }
    

    然后打电话:

    find_coord(lat, lng, function (smart_loc) {
        //
        // YOUR CODE WITH 'smart_loc' HERE
        //
    });
    

相关问题