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.');
}
6
请使用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.
function isBigEnough(element, index, array){
return (element >= 10);
}
var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true
Array.every:
function isBigEnough(element, index, array){
return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true
0
通常没有办法打破javascript中的“each”循环 . 通常可以做的是使用“短路”方法 .
array.forEach(function(item) {
// if the condition is not met, move on to the next round of iteration.
if (!condition) return;
// if the condition is met, do your logic here
console.log('do stuff.')
}
18 回答
据我所知,Angular没有这个函数(它基本上是一个forEach,一旦函数返回true就会突破循环) .
http://underscorejs.org/#find
没有办法做到这一点 . 见https://github.com/angular/angular.js/issues/263 . 根据你正在做的事情,你可以使用布尔值来进入循环体 . 就像是:
angular.forEach
循环在条件匹配时不会中断 .我个人的建议是使用 NATIVE FOR 循环而不是
angular.forEach
.NATIVE FOR循环比其他循环快约 90% .
USE FOR loop IN ANGULAR:
请使用ForEach的部分或全部实例,
一些例子:
每个例子:
查找更多信息
http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/
使用Array Some Method
exists将返回true,您可以将其用作函数中的变量
Array Some Method - Javascript
具体来说,您可以退出
forEach
循环,并在任何地方抛出异常 .但是,最好是使用其他库或实现自己的函数,在这种情况下使用
find
函数,因此您的代码是最高级的 .如果将jQuery(因此不是jqLite)与AngularJS结合使用,则可以使用$ .each进行迭代 - 这允许基于布尔返回值表达式进行断开和继续 .
的jsfiddle:
http://jsfiddle.net/JEcD2/1/
使用Javascript:
Note:
虽然使用jQuery也不错,但MDN推荐使用本机Array.some或Array.every函数,因为您可以在本机forEach文档中阅读:
以下示例由MDN提供:
Array.some:
Array.every:
通常没有办法打破javascript中的“each”循环 . 通常可以做的是使用“短路”方法 .
正如其他答案所述,Angular不提供此功能 . 但是jQuery会这样做,如果你加载了jQuery和Angular,你可以使用
见http://api.jquery.com/jquery.each/
break
无法在angular forEach中实现,我们需要修改forEach来做到这一点 .你可以用这个:
试试这个休息;
我希望通过返回来做到这一点 . 将循环部分放在私有函数中,并在想要中断循环时返回 .
我意识到这是旧的,但阵列过滤器可能会做你需要的:
然后,您可以运行
arr.forEach
和其他数组函数 .我意识到,如果你打算完全减少循环操作,这可能不会做你想要的 . 为此你最好使用
while
.这个例子有效 . 试试吧 .
只需添加$ index并执行以下操作: