我正在構建一個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);
}
希望這是有道理的,並提前感謝!