我有一个角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并没有提供这样的函数。你可能想要为此使用下划线的find()函数(它基本上是一个forEach,一旦函数返回true就会跳出循环)。

http://underscorejs.org/#find

这是不可能的。见https://github.com/angular/angular.js/issues/263。取决于你在做什么,你可以使用布尔值来不进入循环体。喜欢的东西:

var keepGoing = true;
angular.forEach([0,1,2], function(count){
  if(keepGoing) {
    if(count == 1){
      keepGoing = false;
    }
  }
});

我会用return代替break。

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

效果非常好。

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

        }      
    });
});

break在angular forEach中是不可能实现的,我们需要修改forEach来实现。

$scope.myuser = [{name: "Ravi"}, {name: "Bhushan"}, {name: "Thakur"}];  
                angular.forEach($scope.myuser, function(name){
                  if(name == "Bhushan") {
                    alert(name);
                    return forEach.break(); 
                    //break() is a function that returns an immutable object,e.g. an empty string
                  }
                });