Officially, there is no proper way to break out of a forEach loop in javascript. Using the familiar break syntax will throw an error. If breaking the loop is something you really need, it would be best to consider using a traditional loop.
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.
From the official MDN docs: 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.
break ends execution of the current for , foreach , while , do-while or switch structure.
The angular.forEach
loop can't break on a condition match.
My personal advice is to use a NATIVE FOR loop instead of angular.forEach
.
The NATIVE FOR loop is around 90% faster then other for loops.
USE FOR loop IN ANGULAR:
var numbers = [0, 1, 2, 3, 4, 5];
for (var i = 0, len = numbers.length; i < len; i++) {
if (numbers[i] === 1) {
console.log('Loop is going to break.');
break;
}
console.log('Loop will continue.');
}
There's no way to do this. See https://github.com/angular/angular.js/issues/263. Depending on what you're doing you can use a boolean to just not going into the body of the loop. Something like:
var keepGoing = true;
angular.forEach([0,1,2], function(count){
if(keepGoing) {
if(count == 1){
keepGoing = false;
}
}
});
please use some or every instances of ForEach,
Array.prototype.some:
some is much the same as forEach but it break when the callback returns true
Array.prototype.every:
every is almost identical to some except it's expecting false to break the loop.
Example for some:
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.some(function (value, index, _ary) {
console.log(index + ": " + value);
return value === "JavaScript";
});
Example for every:
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.every(function(value, index, _ary) {
console.log(index + ": " + value);
return value.indexOf("Script") > -1;
});
Find more information
http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/
Use the Array Some Method
var exists = [0,1,2].some(function(count){
return count == 1
});
exists will return true, and you can use this as a variable in your function
if(exists){
console.log('this is true!')
}
Array Some Method - Javascript
As far as I know, Angular doesn't provide such a function. You may want to use underscore's find()
function for this (it's basically a forEach which breaks out of the loop once the function returns true).
http://underscorejs.org/#find
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