从嵌套函数返回值(Javascript)

Return value from nested function (Javascript)

本文关键字:Javascript 返回值 嵌套 函数      更新时间:2023-09-26

我需要返回getNearRoutes函数的变量结果。在routes函数中,数组结果包含了所有正确的元素,但当函数结束时,数组结果为空。我知道这是一个范围问题,但我还没有能够解决它,任何帮助是感激的。

提前感谢。

getNearRoutes: function(lat, lng){
    result = [];
    var routes = $.getJSON("js/storage/routes.json", function(json) {
        for(var i = 0; i < json.length; i++) {
            var obj = json[i];   
            for( var j = 0; j < obj.points.length ; j++){
                if (app.calculateDistance( obj.points[j].lat, obj.points[j].lng  , lat , lng) < 0.05) {
                    result.push(obj);
                    break;
                }
             }
         }
    });
    return result;
}

由于getJSON是异步的,您需要一个回调:

getNearRoutes: function(lat, lng, callback){
    var result = [];
    $.getJSON("js/storage/routes.json", function(json) {
        for(var i = 0; i < json.length; i++) {
            var obj = json[i];   
            for( var j = 0; j < obj.points.length ; j++){
                if (app.calculateDistance( obj.points[j].lat, obj.points[j].lng  , lat , lng) < 0.05) {
                    result.push(obj);
                    break;
                }
             }
         }
         callback(result);
    });
}

然后使用函数:

getNearRoutes(lat, lng, function(result) {
    console.log(result); //data is here!
});