为什么这总是返回 false(嵌套的循环)

Why does this always return false (nested for loop)

本文关键字:嵌套 循环 false 返回 为什么      更新时间:2023-09-26

很简单:

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

这是一个(糟糕的)改写的代码段 - 如果我传入一个应该解析为 true 的查询,"返回 true"会被击中,但随后直接跳转返回 false,因此这总是计算为 false。 我做错了什么?

因为你总是返回假。 return true在其他范围内。你应该像这样编写代码:

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

更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope

如果你在逻辑上分解这些,它可能更有意义。虽然不一定是 JavaScript 语法,但想象一下:

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;
    }
}

现在我知道这在实际情况下是行不通的,但是将其分开有助于分离在函数中具有多个功能的想法。如前所述,return true;语句仅适用于wordDo函数,不适用于shouldDoThis函数。

一个好的解决方案可能是从wordDosectionDo返回一些东西,然后在shouldDoThis中检查它。