我有一个角foreach循环,我想打破循环,如果我匹配一个值。下面的代码不能工作。

angular.forEach([0,1,2], function(count){
  if(count == 1){
    break;
  }
});

我怎样才能得到这个?


当前回答

具体地说,您可以退出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

角。在条件匹配的情况下,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.');
}

正如其他答案所说,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/

你可以用这个:

var count = 0;
var arr = [0,1,2];
for(var i in arr){
   if(count == 1) break;
   //console.log(arr[i]);
}

我更喜欢用return来做。将循环部分放在私有函数中,并在想要打破循环时返回。