我的循环没有超过数组中的第一项。我试图这样做,如果一个项目已经在数组中,它将通过它。关于我做错了什么的想法?
function DBController($scope){
$scope.itemName = " ";
$scope.nameArray = ['Bread', 'Milk', 'Eggs'];
$scope.addItem = function(){
console.log($scope.itemName);
for (var i = 0; i < $scope.nameArray.length; i++) {
if ($scope.itemName === " ") {
alert("I'm sorry, but you have to enter an item to add to this list.");
$scope.itemName = " ";
break;
}else if ($scope.itemName === $scope.nameArray[i]){
alert("I'm sorry, but the item you are trying to add is already in your list.");
$scope.itemName = " ";
break;
}else{
$scope.nameArray.push($scope.itemName);
$scope.itemName = " ";
break;
};
};
}
$scope.deleteName = function(deletedName){
var idx = $scope.nameArray.indexOf(deletedName);
$scope.nameArray.splice(idx, 1);
}
}
答案 0 :(得分:1)
break语句终止循环。请参阅here。
答案 1 :(得分:0)
你的循环逻辑有点错误。第一次迭代后,新的itemName被添加到数组中(如果不是面包)并且您的代码打破了循环请参见@ http://jsbin.com/huyul/2/edit?html,js,output
$scope.addItem = function(){
console.log($scope.itemName);
for (var i = 0; i < $scope.nameArray.length; i++) {
if ($scope.itemName === " ") {
alert("I'm sorry, but you have to enter an item to add to this list.");
$scope.itemName = " ";
return;
}else if ($scope.itemName === $scope.nameArray[i]){
alert("I'm sorry, but the item you are trying to add is already in your list.");
$scope.itemName = " ";
return;
}
}
$scope.nameArray.push($scope.itemName);
$scope.itemName = " ";
};