gpt4 book ai didi

javascript - 为什么这总是返回 false(嵌套 for 循环)

转载 作者:行者123 更新时间:2023-11-30 10:27:48 26 4
gpt4 key购买 nike

这很简单:

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。我做错了什么?

最佳答案

因为你总是返回错误。 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 - 为什么这总是返回 false(嵌套 for 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18771256/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com