Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmberJS: is it possible to break from forEach?

Tags:

ember.js

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

like image 960
PJC Avatar asked Feb 25 '13 17:02

PJC


People also ask

How do you break out of a forEach loop?

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.

How do you break out of forEach TypeScript?

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!

How do you break a forEach loop in angular 9?

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; });


2 Answers

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

like image 68
ThomasDurin Avatar answered Oct 10 '22 09:10

ThomasDurin


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

like image 32
James A. Rosen Avatar answered Oct 10 '22 11:10

James A. Rosen