我正在构建一个Angular/Javascript/Ionic/Cordova应用程序。从阵列中获取ID,存储它并将其从本地删除
我有一个功能,其中我所说的下面阵列被存储作为变量(existingEntries)
categories: Array [276]
[0...99]
0: Object
id: 288
exclude: false
1: Object
id: 320
exclude: true
该函数检索所有阵列中的元件,以查看是否值排除被设置为真或假
var existingEntries = $scope.categoryList;
if(existingEntries == null) existingEntries = [];
for (var i = 0; i < existingEntries.length; i++) {
if (existingEntries[i]['exclude'] == true) {
$scope.addLocalExcludedCategories(i);
} else if (existingEntries[i]['exclude'] == false) {
$scope.removeLocalExcludedCategories(i);
}
}
一旦完成了其他相关函数(addLocal ..和remove Local ...)被调用来存储id的。下面是addLocal ..函数,它可以工作,但是当我反复运行这些代码时,我得到了重复,并且我确信它可以更好地编码。我正在使用localstorage,因为我需要将数组保存到本地,但如果您有其他解决方案,那将非常棒。
$scope.addLocalExcludedCategories = function(catID) {
console.log("addLocalExcludedCategories Called")
//Add Item to Excluded Categories Variable
var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories"));
if(existingEntries == null) existingEntries = [];
var entryId = catID;
var entry = {
'id': entryId,
};
existingEntries.push(entry);
window.localStorage.setItem("ExcludedCategories", JSON.stringify(existingEntries));
$scope.ExcludedCategories = window.localStorage.getItem("ExcludedCategories");
}
此外,这里是删除功能,因为我发现ID的排除值设置为true,而不是假的预期工作。
$scope.removeLocalExcludedCategories = function(catID) {
console.log("removeLocalExcludedCategories Called")
//Remove Item to Excluded Categories Variable
var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories"));
if(existingEntries == null) existingEntries = [];
for (var i = 0; i < existingEntries.length; i++) {
if (existingEntries[i]['id'] == catID) {
console.log(i);
existingEntries.splice(i, 1);
}
}
//console.log("Remove Categories >>>");
//console.log(existingEntries);
window.localStorage.setItem("ExcludedCategories", JSON.stringify(existingEntries));
$scope.ExcludedCategories = window.localStorage.getItem("ExcludedCategories");
console.log($scope.ExcludedCategories);
}
希望这是有道理的,并提前感谢!