简体   繁体   English

从匿名内部函数返回

[英]Return from anonymous inner function

There are many related questions, none have the answer that helped me. 有很多相关的问题,没有一个问题对我有帮助。 In other words, questions are specific to a scenario and not isolated to issue. 换句话说,问题是特定于场景的,不是孤立地发出的。 hence my question here: 因此,我的问题在这里:

I have a JavaScript function. 我有一个JavaScript函数。 Uses jQuery. 使用jQuery。 I'm using an anonymous function in $.each() loop to find the object I want and return to the caller. 我在$ .each()循环中使用匿名函数来查找所需的对象并返回到调用方。 Need help to figure out how to return from an inner function that is anonymous. 需要帮助找出如何从匿名的内部函数返回。

functions.findRider = function(riderId){
    $.each(app.riders, function(index, result) {
        if (result["id"] == riderId) {
            console.log("found the rider:"+JSON.stringify(result));
            return result;
        }
    });
    console.log("Did not find rider");
}

app.riders is an array of objects. app.riders是一个对象数组。 Each object in the array have an Id. 数组中的每个对象都有一个ID。

The easiest way would be to create a variable outside the $.each() function and add to it from inside the loop: 最简单的方法是在$.each()函数外部创建一个变量,然后从循环内部将其添加到其中:

functions.findRider = function(riderId){
    var results = [];
    $.each(app.riders, function(index, result) {
        if (result["id"] == riderId) {
            console.log("found the rider:"+JSON.stringify(result));
            results.push(result);
        }
    });
    console.log("Did not find rider");
}

As far as I know (but I might be mistaken), there is no way to return from an anonymous function like this. 据我所知(但我可能会误会),没有办法从这样的匿名函数中返回。

You can use .filter for this kinda search 您可以使用.filter进行这种搜索

like this 像这样

functions.findRider = function(riderId) {
    var data = app.riders.filter(function(x) {
        return x.id == riderId;
    });
    return data.length > 0 ? data[0] : null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM