Is there a way to break from the forEach iterator in Ember?
I tried to return false in the callback (a la jQuery) but it does not work.
Thanks! PJ
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.
To break a forEach() loop in TypeScript, throw and catch an error by wrapping the call to the forEach() method in a try/catch block. When the error is thrown, the forEach() method will stop iterating over the collection. Copied!
Use every() instead of forEach() every(v => { if (v > 3) { return false; } console. log(v); // Make sure you return true. If you don't return a value, `every()` will stop. return true; });
You can use Array#some
or Array#every
[1,2,3].some(function(element) {
return true; // Break the loop
});
[1,2,3].every(function(element) {
return false; // Break the loop
});
More informations here
Ember uses the native Array.prototype.forEach
if it's available, and emulates it if not. See https://github.com/emberjs/ember.js/blob/v1.0.0-rc.1/packages/ember-metal/lib/array.js#L45.
JavaScript's forEach
doesn't support breaking. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With