我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
我怎样才能得到这个?
我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。
angular.forEach([0,1,2], function(count){
if(count == 1){
break;
}
});
我怎样才能得到这个?
当前回答
我更喜欢用return来做。将循环部分放在私有函数中,并在想要打破循环时返回。
其他回答
你可以用这个:
var count = 0;
var arr = [0,1,2];
for(var i in arr){
if(count == 1) break;
//console.log(arr[i]);
}
如果你将jQuery(而不是jqLite)与AngularJS结合使用,你可以使用$进行迭代。Each -允许根据布尔返回值表达式中断和继续。
JSFiddle:
http://jsfiddle.net/JEcD2/1/
Javascript:
var array = ['foo', 'bar', 'yay'];
$.each(array, function(index, element){
if (element === 'foo') {
return true; // continue
}
console.log(this);
if (element === 'bar') {
return false; // break
}
});
注意:
虽然使用jQuery还不错,但都是原生数组。some或Array。每个函数都是MDN推荐的,你可以在原生forEach文档中阅读:
“没有办法停止或打破forEach循环。解决方案是使用Array。every或Array.some"
MDN提供了以下例子:
Array.some:
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
使用Array Some方法
var exists = [0,1,2].some(function(count){
return count == 1
});
Exists将返回true,您可以将其用作函数中的变量
if(exists){
console.log('this is true!')
}
数组一些方法- Javascript
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)
}
}
});
});
正如其他答案所说,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/