在我的angularjs应用程序中,我需要手动从数据数组中删除或添加旧数据/新数据(服务在循环中执行)。对于remove,我使用slice();但有一个问题:该项被正确删除,但execVerif_distant();不为下一个项目执行。使用我的实际代码execVerif_distant();对于每个项目只执行一半时间。例如,如果我需要移除整个数组,那么只移除一半。
// start the loop, search in local datas
angular.forEach($scope.seaDocument.datas.cages, function(itemLocalCages) {
execVerif_local(itemLocalCages.url);
});
function execVerif_local(identifiant) {
var iterSearch_local = 0;
angular.forEach(responseZS, function(itemDistantCages) {
if (itemDistantCages.url == identifiant) {
iterSearch_local++;
}
});
// if we not find the local datas in distant datas
if (iterSearch_local == 0) {
// verifItem(); call
verifItem('remove', identifiant);
}
}
// verifItem();
function verifItem(action, url) {
if (action == 'remove') {
var iIndex = -1;
angular.forEach($scope.seaDocument.datas.cages, function(itemLocalCages) {
iIndex++;
if (itemLocalCages.url == url) {
$scope.seaDocument.datas.cages.splice(iIndex,1);
}
});
} else {
// do nothing
}
}
怎么了?
问题是foreach
正在对要从中删除内容的同一对象进行迭代。为了避免这种行为,在循环之前克隆您正在迭代的对象,并将它们作为单独的对象进行处理:
// ... code
var arrCopy = $scope.seaDocument.datas.cages.slice(); //this will create a deep copy.
angular.forEach(arrCopy, function(itemLocalCages) {
iIndex++;
if (itemLocalCages.url == url) {
$scope.seaDocument.datas.cages.splice(iIndex,1);
}
});
//... more code