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

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

我怎样才能得到这个?


当前回答

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

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

其他回答

试试这个作为休息;

angular.forEach([0,1,2], function(count){
  if(count == 1){
    return true;
  }
});
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代替break。

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

效果非常好。

通常在javascript中没有办法打破“each”循环。 通常能做的是使用“短路”法。

array.forEach(函数(项){ //如果条件不满足,则继续进行下一轮迭代。 If (!condition)返回; //如果条件满足,在这里做你的逻辑 console.log(“做东西。”) }

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