Skip to content Skip to sidebar Skip to footer

Breaking Out Of An Inner Foreach Loop

I am trying to break out of an inner foreach loop using JavaScript/jQuery. result.history.forEach(function(item) { loop2: item.forEach(function(innerItem) { console

Solution 1:

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

someArray.every(function(element) {
  if (timeToStop(element)) // or whateverreturnfalse;
  // do stuff// ...returntrue; // keep iterating
});

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

Solution 2:

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.

Post a Comment for "Breaking Out Of An Inner Foreach Loop"