关于angularjs:Angular JS Break ForEach

Angular JS break ForEach

我有一个有角度的foreach循环,如果我匹配一个值,我想摆脱循环。 以下代码不起作用。

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

我怎么能得到这个?


angular.forEach循环在条件匹配时不会中断。

我的个人建议是使用NATIVE FOR循环而不是angular.forEach

NATIVE FOR循环比其他for循环快90%。

For loop break , for loop test result

在语言中使用FOR循环:

1
2
3
4
5
6
7
8
9
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.');
}


没有办法做到这一点。参见https://github.com/angular/angular.js/issues/263。根据您正在执行的操作,可以使用布尔值来不进入循环的主体。就像是:

1
2
3
4
5
6
7
8
var keepGoing = true;
angular.forEach([0,1,2], function(count){
  if(keepGoing) {
    if(count == 1){
      keepGoing = false;
    }
  }
});


请使用ForEach的部分或每个实例,

1
2
3
4
5
Array.prototype.some:
some is much the same as forEach but it break when the callback returns true

Array.prototype.every:
every is almost identical to some except it's expecting false to break the loop.

一些示例:

1
2
3
4
5
6
var ary = ["JavaScript","Java","CoffeeScript","TypeScript"];

ary.some(function (value, index, _ary) {
    console.log(index +":" + value);
    return value ==="JavaScript";
});

每个示例:

1
2
3
4
5
6
var ary = ["JavaScript","Java","CoffeeScript","TypeScript"];

ary.every(function(value, index, _ary) {
    console.log(index +":" + value);
    return value.indexOf("Script") > -1;
});

查找更多信息
http://www.jsnoob.com/2013/11/26/how-to-break-the-foreach/


使用某些数组

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

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

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

数组某种方法-Javascript


如果将jQuery(因此不是jqLit??e)与AngularJS结合使用,则可以使用$ .each进行迭代-允许基于布尔返回值表达式进行中断和继续。

JSFiddle:

http://jsfiddle.net/JEcD2/1/

Javascript:

1
2
3
4
5
6
7
8
9
10
var array = ['foo', 'bar', 'yay'];
$.each(array, function(index, element){
    if (element === 'foo') {
        return true; // continue
    }
    console.log(this);
    if (element === 'bar') {
        return false; // break
    }
});

注意:

尽管使用jQuery还不错,但是MDN推荐使用本机Array.some或Array.every函数,您可以在本机forEach文档中阅读:

"There is no way to stop or break a forEach loop. The solution is to use Array.every or Array.some"

MDN提供了以下示例:

Array.some:

1
2
3
4
5
6
7
function isBigEnough(element, index, array){
    return (element >= 10);
}
var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true

Array.Every:

1
2
3
4
5
6
7
function isBigEnough(element, index, array){
    return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true

具体来说,您可以退出forEach循环,并且在任何地方都可以引发异常。

1
2
3
4
5
6
7
try {
   angular.forEach([1,2,3], function(num) {
      if (num === 2) throw Error();
   });
} catch(e) {
    // anything
}

但是,最好使用其他库或实现自己的函数(在这种情况下为find函数),因此您的代码是最高级的。


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

http://underscorejs.org/#find


试试这个作为休息;

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

正如其他答案所述,Angular不提供此功能。 jQuery可以,但是如果您已经加载了jQuery和Angular,则可以使用

1
2
3
jQuery.each ( array, function ( index, value) {
    if(condition) return false; // this will cause a break in the iteration
})

参见http://api.jquery.com/jquery.each/


通常,没有办法打破javascript中的"每个"循环。
通常可以使用"短路"方法。

1
2
3
4
5
6
7
    array.forEach(function(item) {
      // if the condition is not met, move on to the next round of iteration.
      if (!condition) return;

      // if the condition is met, do your logic here
      console.log('do stuff.')
    }


break不可能在角度forEach中实现,我们需要修改forEach来实现。

1
2
3
4
5
6
7
8
$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
                  }
                });


您可以使用此:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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中断循环。

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


1
2
3
4
5
6
7
8
9
10
11
12
13
$scope.arr = [0, 1, 2];  
$scope.dict = {}
for ( var i=0; i < $scope.arr.length; i++ ) {
    if ( $scope.arr[i] == 1 ) {
        $scope.exists = 'yes, 1 exists';
        break;
    }
 }
 if ( $scope.exists ) {
     angular.forEach ( $scope.arr, function ( value, index ) {
                      $scope.dict[index] = value;
     });
 }

我希望通过返回来做到这一点。将循环部分放入私有函数中,并在需要中断循环时返回。


这个例子有效。尝试一下。

1
2
3
4
5
6
var array = [0,1,2];
for( var i = 0, ii = array.length; i < ii; i++){
  if(i === 1){
   break;
  }
}


我意识到这很旧,但是数组过滤器可能会满足您的要求:

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

然后,您可以运行arr.forEach和其他数组函数。

我意识到,如果您打算完全减少循环操作,那么这可能不会做您想要的。为此,最好使用while


我会使用return而不是break

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

奇迹般有效。


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

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