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

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

我怎样才能得到这个?


当前回答

我知道这是旧的,但数组过滤器可以满足你的需要:

var arr = [0, 1, 2].filter(function (count) {
    return count < 1;
});

然后你可以运行arr。forEach和其他数组函数。

我意识到,如果你打算完全减少循环操作,这可能不会达到你想要的效果。所以你最好趁现在。

其他回答

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)
            }

        }      
    });
});

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

只需添加$index并执行以下操作:

angular.forEach([0,1,2], function(count, $index) {
     if($index !== 1) {
          // do stuff
     }
}

使用Return打破循环。

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

据我所知,Angular并没有提供这样的函数。你可能想要为此使用下划线的find()函数(它基本上是一个forEach,一旦函数返回true就会跳出循环)。

http://underscorejs.org/#find