简体   繁体   English

函数中的“返回”,如果Lodash forEach中的语句()

[英]“Return” out of Function, If Statement Inside Lodash forEach()

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. 看起来很简单 - 尝试检查每个项目的某些条件,如果没有满足任何项目退出函数并返回false。 When loop is done without exiting, return true. 在没有退出的情况下完成循环时,返回true。

Always returns true, tried console logging, and it does hit the "return false" point. 始终返回true,尝试使用控制台日志记录,并且确实返回“返回错误”点。

Am I missing something obvious about how js works or is this a lodash thing? 我是否遗漏了一些关于js如何工作的明显事实或者这是一个lodash的事情?

What you're missing is that your return false statement is inside a different function than your return true statement. 你遗漏的是你的return false语句与你的return true语句不同。 You probably want to use a different lodash method like any / some . 您可能希望使用与any / some不同的lodash方法。

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. 那是因为有2个函数,第二个函数的返回不会使第一个函数返回。 You should set a variable as true and change it to false if the condition is met: 您应该将变量设置为true,并在满足条件时将其更改为false:

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 快速浏览一下,“return”将从内部函数返回false,该函数对列表的每个元素执行一次(通过forEach),而不是退出外部函数

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) 事实上,我认为forEach将继续执行(不确定它的语义,也许它从它调用的函数中寻找一个“错误”结果来打破循环)

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 但是在forEach为true之前设置一个名为result的变量,在if中将其设置为false,然后在结尾处有一个返回结果

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) 应该工作,但你应该检查有关forEach的文档,看看确实做“返回false”会打破循环,或者是否有一些中断或类似命令来执行它(可能是_.break();但我'我不确定那个“_”实例是什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM