Return from a method in which forEach() array method was called. JavaScript

前端 未结 4 1265
情深已故
情深已故 2021-01-28 07:19

I am using forEach() method called from an array in JavaScript. When I write return; somewhere inside the method which is called for every element in array I return

4条回答
  •  佛祖请我去吃肉
    2021-01-28 07:35

    To quote Mozilla Developer Network:

    There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a Boolean return value, you can use every() or some() instead. If available, the new methods find() or findIndex() can be used for early termination upon true predicates as well.

    Having said that, I believe your solution to have set a flag to return out of the function is the most appropriate and simple.

提交回复
热议问题