我尝试为课程创建标记列表。当我为每个学生输入分数时, 推送活动有效。每次更改时,都会在数组中创建重复项。我该如何解决这个问题?
angular.element(document).ready(function() {
$scope.ArrayMarks = [];
$scope.ArrayMarks.push({
'subject': '',
'student': '',
'mark': '',
});
$scope.internal = function(Sub, Std, score) {
if ($scope.ArrayMarks[0].subject === '' && $scope.ArrayMarks[0].student === '') {
$scope.ArrayMarks.push({
'subject': Sub,
'student': Std,
'mark': score,
});
$scope.ArrayMarks.splice(0, 1);
} else {
for (var i = 0; i < $scope.ArrayMarks.length; i++) {
if ($scope.ArrayMarks[i].subject === Sub && $scope.ArrayMarks[i].student === Std) {
$scope.ArrayMarks[i].mark = score;
} else {
$scope.ArrayMarks.push({
'subject': Sub,
'student': Std,
'mark': score,
});
}
}
}
};
bottom:0
答案 0 :(得分:3)
只需更新for
循环,并确保仅在未找到更新条目时才添加新条目。如果没有找到更新条目,您当前的解决方案会在每个循环中添加新条目。
$scope.internal = function(Sub, Std, score) {
if ($scope.ArrayMarks[0].subject === '' && $scope.ArrayMarks[0].student === '') {
$scope.ArrayMarks.push({
'subject': Sub,
'student': Std,
'mark': score,
});
$scope.ArrayMarks.splice(0, 1);
} else {
var found = false;
for (var i = 0; i < $scope.ArrayMarks.length; i++) {
if ($scope.ArrayMarks[i].subject === Sub && $scope.ArrayMarks[i].student === Std) {
$scope.ArrayMarks[i].mark = score;
found = true;
}
}
if (!found) {
$scope.ArrayMarks.push({
'subject': Sub,
'student': Std,
'mark': score,
});
}
}
};