$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无效,请指导
答案 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;
}
}
});