角度的Foreach循环过程和检查条件

时间:2018-08-03 11:15:11

标签: angularjs foreach

$scope.users = [{
    user_id: 101,
    type: 2,
    name: "Harry"
  },
  {
    user_id: 102,
    type: 2,
    name: "James"
  }
];

$scope.item = {
  id: 10,
  type: 3
};

angular.forEach($scope.users, function(value, key) {
  if (value.type != $scope.item.type) {
    console.log('Sorry this is not for you!');
    return false;
  }
}); 

让我们确认是否与条件不符,应该返回控制台并退出

尝试休息;关键字并返回false无效,请指导

2 个答案:

答案 0 :(得分:1)

使用本机for循环而不是角度forEach。它速度更快,可让您根据条件打破循环。下面的示例:

var test = function() {
    var users = [{
            user_id: 101,
            type: 2,
            name: "Harry"
        },
        {
            user_id: 102,
            type: 2,
            name: "James"
        }
    ];
    var item = {
        id: 10,
        type: 3
    };
    for (var i = 0; i < users.length; i++) {
        if (users[i].type != item.type) {
            console.log('breaking');
            break;
        }
    }
}

答案 1 :(得分:0)

尝试

var keepGoing = true;
angular.forEach($scope.users, function(value, key) {

if (keepGoing) {
     if (value.type != $scope.item.type) {
console.log('Sorry this is not for you!');
keepGoing = false;
//return false;
    }
  }
});