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

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

我怎样才能得到这个?


当前回答

使用Array Some方法

 var exists = [0,1,2].some(function(count){
      return count == 1
 });

Exists将返回true,您可以将其用作函数中的变量

if(exists){
    console.log('this is true!')
}

数组一些方法- Javascript

其他回答

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

        }      
    });
});

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

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

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

我会用return代替break。

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

效果非常好。