Reputation: 2551
I have a nested foreach which I want to break out of if a condition is met. It seems that using a return means that the execution breaks out of the outer foreach, not the inner:
angular.forEach(objectA, function(objA, key) {
angular.forEach(ObjectB, function(objB, key) {
if(foo !== bar) {
return;
}
});
});
I read that it is better to use s native for each for this purpose, so I created this fiddle which works as I need it to:
https://jsfiddle.net/3dfx14nt/
However when I apply the logic to my Angular app it behaves in the same way as the Angular.foreach does. When returning on the inner foreach it breaks out to the outer foreach.
Upvotes: 0
Views: 365
Reputation: 29
forEach
accepts a function and runs it for every element in the array. You can't break the loop. If you want to exit from a single run of the function, you use return
forEach
doesn't support break, you should use return
If you want to be able to break the loop, you have to use for..of
loop:
for(let name of group.names){
if (name == 'SAM') {
break;
}
}
Upvotes: 1