Breaking out of an inner foreach loop

前端 未结 2 2034
终归单人心
终归单人心 2020-12-19 11:58

I am trying to break out of an inner foreach loop using JavaScript/jQuery.

result.history.forEach(function(item) {
    loop2:
    item.forEach(function(inner         


        
相关标签:
2条回答
  • 2020-12-19 12:22

    If you need to be able to break an iteration, use .every() instead of .forEach():

    someArray.every(function(element) {
      if (timeToStop(element)) // or whatever
        return false;
      // do stuff
      // ...
      return true; // keep iterating
    });
    

    You could flip the true/false logic and use .some() instead; same basic idea.

    0 讨论(0)
  • 2020-12-19 12:32

    Can't do it. According to MDN:

    There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, 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.

    0 讨论(0)
提交回复
热议问题