我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
我怎样才能得到这个?
我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
我怎样才能得到这个?
当前回答
据我所知,Angular并没有提供这样的函数。你可能想要为此使用下划线的find()函数(它基本上是一个forEach,一旦函数返回true就会跳出循环)。
http://underscorejs.org/#find
其他回答
我更喜欢用return来做。将循环部分放在私有函数中,并在想要打破循环时返回。
角。在条件匹配的情况下,forEach循环不能中断。
我个人的建议是使用NATIVE FOR循环而不是angular.forEach。
NATIVE FOR循环比其他FOR循环快90%左右。
在ANGULAR中使用FOR循环:
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.');
}
使用Return打破循环。
angular.forEach([0,1,2], function(count){
if(count == 1) {
return;
}
});
试试这个作为休息;
angular.forEach([0,1,2], function(count){
if(count == 1){
return true;
}
});
我会用return代替break。
angular.forEach([0,1,2], function(count){
if(count == 1){
return;
}
});
效果非常好。