简体   繁体   中英

Why does this always return false (nested for loop)

It's pretty simple:

var shouldDoThis = function(query) {
    documents.forEach(function(section) {
        section.words.forEach(function(word) {
            if (word.content == query.content) {
                return true;
            }
        });
    });
    return false;
};

This is a (poorly) reworded snippet - if I pass in a query that should resolve to true, 'return true' gets hit but then jumps right to return false, so this always evaluates to false. What am I doing wrong?

Because you are returning false always. return true is on other scope. You should write your code like this:

var shouldDoThis = function(query) { // 1st level
    var should;
    documents.forEach(function(section) { // 2nd level
        section.words.forEach(function(word) { //3rd level
            if (word.content == query.content) {
                should = true;
                return; // you "quit" the 3rd level function. This returns to 2nd level
            }
        }); // end of 3rd level
    }); // end of 2nd level

    return should;
}; // end of 1st level

More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope

If you were to logically break these up, it might make more sense. Although not necessarily JavaScript syntax, imagine this:

function shouldDoThis(query) {
    documents.forEach(sectionDo);
    return false;
}

function sectionDo(section) {
    section.words.forEach(wordDo);
}

function wordDo(word) {
    if (word.content == query.content) {
        return true;
    }
}

Now I know this wouldn't work in a real situation, but breaking it apart helps separate the idea of having multiple functions within functions. As had been mentioned, the return true; statement only applies to the wordDo function, not the shouldDoThis function.

A good solution could involve returning something from wordDo , sectionDo , and then checking that in shouldDoThis .

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