1

这很简单:

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

这是一个(糟糕的)改写的片段 - 如果我传入一个应该解析为 true 的查询,'return true' 会被命中,但随后会向右跳转以返回 false,所以这总是评估为 false。我究竟做错了什么?

4

2 回答 2

4

因为你总是返回 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

于 2013-09-12T18:03:59.477 回答
0

如果您要在逻辑上将它们分解,可能会更有意义。虽然不一定是 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函数。

一个好的解决方案可能包括从wordDo,中返回某些sectionDo内容,然后将其签入shouldDoThis.

于 2013-09-12T18:08:44.287 回答