问题
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
回答1:
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
回答2:
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
回答3:
Nope, I dont think so cfr James, looking at the foreach code, you can see that it uses a for loop under the hood. You can throw an exception, but thats like writing spagetti code. But it might be possible, you can do a feature request at github? Or write your own implementation that breaks in the for loop.
回答4:
Use Array#find and return true to break out of the loop.
回答5:
Using toArray can potentially remove the order of the array, which sort of defeats the purpose. You could use a normal for loop but use objectAt to make it work for you.
var emberArray = [ ... Array of Ember objects ... ],
min = 3,
max = emberArray.get('length'),
targetObject;
for( var i = min; i < max; i++ ){
targetObject = emberArray.objectAt( i );
if( targetObject.get('breakHere') ) {
break;
}
}
This has the added benefit of allowing you to start at a certain index, so you can loop through the smallest number of items.
来源:https://stackoverflow.com/questions/15072278/emberjs-is-it-possible-to-break-from-foreach