简体   繁体   中英

Why would my find method return undefined?

I'm recreating a number of Underscore.js methods to study JavaScript and programming in general.

Below is my attempts to recreate Underscore's _.find() method.

var find = function(list, predicate) { // Functional style
    _.each(list, function(elem){
        if (predicate(elem)) {
            return elem;
        }
    });
};

var find = function(list, predicate) { // Explicit style
    if (Array.isArray(list)) {
        for (var i = 0; i < list.length; i++) {
            if (predicate(list[i])) {
                return list[i];
            }
        }
    } else {
        for (var key in list) {
            if (predicate(list[key])) {
                return list[key];
            }
        }
    }
};

My second find method, which is using for loop and for in loop works. Whereas, my first find method would return undefined . I believe both should do the same work. However, they don't. Would someone please point what is going on?

Your return is only returning from the inner (nested) function and your find function is indeed not returning anything, hence the undefined .

Try this instead:

var find = function(list, predicate) { // Functional style
    var ret;

    _.each(list, function(elem){
        if (!ret && predicate(elem)) {
            return ret = elem;
        }
    });

    return ret;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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