264

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

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

我怎样才能得到这个?

4

21 回答 21

302

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

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

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

for loop break , for loop 测试结果

在角度使用 FOR 循环:

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.');
}
于 2013-10-17T11:08:46.703 回答
275

没有办法做到这一点。请参阅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;
    }
  }
});
于 2012-12-12T16:45:21.597 回答
25

请使用 ForEach 的部分或所有实例,

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.

一些例子:

var ary = ["JavaScript", "Java", "CoffeeScript", "TypeScript"];

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

每个示例:

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/

于 2015-07-07T12:31:45.827 回答
19

使用数组一些方法

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

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

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

数组一些方法 - Javascript

于 2013-11-01T23:06:10.827 回答
6

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

http://underscorejs.org/#find

于 2012-12-12T16:33:55.263 回答
6

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

JSF中:

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

Javascript:

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.someArray.every函数,您可以在原生forEach文档中阅读:

“没有办法停止或中断 forEach 循环。解决方案是使用 Array.every 或 Array.some”

以下示例由 MDN 提供:

数组.一些:

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

数组.每个:

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
于 2014-06-04T04:59:55.063 回答
6

具体来说,你可以退出一个forEach循环,在任何地方都可以抛出异常。

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

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

于 2015-07-15T16:50:16.093 回答
5

试试这个作为休息;

angular.forEach([0,1,2], function(count){
  if(count == 1){
    return true;
  }
});
于 2017-05-15T20:06:22.830 回答
3

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

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

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

于 2015-09-11T14:45:33.917 回答
3

通常没有办法打破javascript中的“每个”循环。通常可以做的是使用“短路”方法。

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

于 2015-10-01T04:01:59.003 回答
2

break在角度 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
                  }
                });
于 2015-09-23T11:13:07.023 回答
2

你可以使用这个:

var count = 0;
var arr = [0,1,2];
for(var i in arr){
   if(count == 1) break;
   //console.log(arr[i]);
}
于 2016-06-23T08:32:51.040 回答
1
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)
            }

        }      
    });
});
于 2015-08-07T07:31:39.613 回答
0
$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;
     });
 }
于 2016-08-07T21:04:04.030 回答
0

我宁愿通过返回来做到这一点。将循环部分放在私有函数中,并在您想中断循环时返回。

于 2016-09-02T04:43:39.710 回答
0

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

var array = [0,1,2];
for( var i = 0, ii = array.length; i < ii; i++){
  if(i === 1){
   break;
  }
}
于 2016-12-29T14:24:49.957 回答
0

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

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

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

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

于 2017-01-19T12:04:49.340 回答
0

我会使用return而不是break.

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

奇迹般有效。

于 2019-01-18T07:21:09.013 回答
0

使用 Return 来中断循环。

angular.forEach([0,1,2], function(count){
  if(count == 1) {
    return;
  }
});
于 2019-08-01T05:34:10.127 回答
0
onSelectionChanged(event) {
    let selectdata = event['api']['immutableService']['gridOptionsWrapper']['gridOptions']['rowData'];
    let selected_flag = 0;

    selectdata.forEach(data => {
      if (data.selected == true) {
        selected_flag = 1;
      }
    });

    if (selected_flag == 1) {
      this.showForms = true;
    } else {
      this.showForms = false;
    }
}
于 2020-02-04T05:11:32.117 回答
-2

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

angular.forEach([0,1,2], function(count, $index) {
     if($index !== 1) {
          // do stuff
     }
}
于 2015-06-25T15:35:20.470 回答