我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
我怎样才能得到这个?
我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
我怎样才能得到这个?
当前回答
请使用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.
例如:
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.some(function (value, index, _ary) {
console.log(index + ": " + value);
return value === "JavaScript";
});
每个的例子:
var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];
ary.every(function(value, index, _ary) {
console.log(index + ": " + value);
return value.indexOf("Script") > -1;
});
查找更多信息 http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/
其他回答
正如其他答案所说,Angular不提供这个功能。而jQuery可以,如果你已经加载了jQuery和Angular,你就可以使用它
jQuery.each ( array, function ( index, value) {
if(condition) return false; // this will cause a break in the iteration
})
参见http://api.jquery.com/jquery.each/
$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函数)会更好,因此您的代码是最高级别的。
使用Array Some方法
var exists = [0,1,2].some(function(count){
return count == 1
});
Exists将返回true,您可以将其用作函数中的变量
if(exists){
console.log('this is true!')
}
数组一些方法- Javascript
据我所知,Angular并没有提供这样的函数。你可能想要为此使用下划线的find()函数(它基本上是一个forEach,一旦函数返回true就会跳出循环)。
http://underscorejs.org/#find