我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
我怎样才能得到这个?
我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
我怎样才能得到这个?
当前回答
这是不可能的。见https://github.com/angular/angular.js/issues/263。取决于你在做什么,你可以使用布尔值来不进入循环体。喜欢的东西:
var keepGoing = true;
angular.forEach([0,1,2], function(count){
if(keepGoing) {
if(count == 1){
keepGoing = false;
}
}
});
其他回答
$scope.arr = [0, 1, 2];
$scope.dict = {}
for ( var i=0; i < $scope.arr.length; i++ ) {
if ( $scope.arr[i] == 1 ) {
$scope.exists = 'yes, 1 exists';
break;
}
}
if ( $scope.exists ) {
angular.forEach ( $scope.arr, function ( value, index ) {
$scope.dict[index] = value;
});
}
具体地说,您可以退出forEach循环,并在任何位置抛出异常。
try {
angular.forEach([1,2,3], function(num) {
if (num === 2) throw Error();
});
} catch(e) {
// anything
}
但是,如果您使用其他库或实现自己的函数(在这种情况下是find函数)会更好,因此您的代码是最高级别的。
我知道这是旧的,但数组过滤器可以满足你的需要:
var arr = [0, 1, 2].filter(function (count) {
return count < 1;
});
然后你可以运行arr。forEach和其他数组函数。
我意识到,如果你打算完全减少循环操作,这可能不会达到你想要的效果。所以你最好趁现在。
我会用return代替break。
angular.forEach([0,1,2], function(count){
if(count == 1){
return;
}
});
效果非常好。
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
var keepGoing = true;
ary.forEach(function(value, index, _ary) {
console.log(index)
keepGoing = true;
ary.forEach(function(value, index, _ary) {
if(keepGoing){
if(index==2){
keepGoing=false;
}
else{
console.log(value)
}
}
});
});