最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - "Return" out of Function, If Statement Inside Lodash forEach() - Stack Overflow

programmeradmin0浏览0评论
function(){
    _.forEach(listOfSomething, function (something) {
      if(someCondition){
        return false
      }
    });
    return true;
}

Looks simple enough - trying to check each item for some condition, if it isn't met for any item exit out of function and return false. When loop is done without exiting, return true.

Always returns true, tried console logging, and it does hit the "return false" point.

Am I missing something obvious about how js works or is this a lodash thing?

function(){
    _.forEach(listOfSomething, function (something) {
      if(someCondition){
        return false
      }
    });
    return true;
}

Looks simple enough - trying to check each item for some condition, if it isn't met for any item exit out of function and return false. When loop is done without exiting, return true.

Always returns true, tried console logging, and it does hit the "return false" point.

Am I missing something obvious about how js works or is this a lodash thing?

Share Improve this question asked Oct 23, 2015 at 21:08 VSOVSO 12.6k28 gold badges115 silver badges200 bronze badges 1
  • You have two functions here. The "return false" inside of the forEach statement affects the inner function and not the outer function. – Jon Trauntvein Commented Oct 23, 2015 at 21:10
Add a comment  | 

3 Answers 3

Reset to default 12

What you're missing is that your return false statement is inside a different function than your return true statement. You probably want to use a different lodash method like any/some.

function(){
    return _.some(listOfSomething, function (something) {
      return someCondition;
    });
}

Thats because there are 2 functions, the return of the second function won't make the first function return. You should set a variable as true and change it to false if the condition is met:

function(){
    var condition = true;
    _.forEach(listOfSomething, function (something) {
      if(someCondition){
        condition = false;
        return;
      }
    });
    return condition;
}

Taking a quick look at it, the "return" will just return false from the inner function that is executed once for every element of the list (via the forEach), not exit the outer function

In fact, I think the forEach will keep on executing (not sure about its semantics, maybe it looks for a "false" result from the function it calls to break the loop)

but set a variable called result before the forEach to true and in the if set it to false, then at the end have a return result

that should work, but you should check the docs about that forEach to see if indeed doing a "return false" will break the loop, or if there's some break or similar command to do it (maybe _.break(); but I'm not sure what that "_" instance is)

发布评论

评论列表(0)

  1. 暂无评论