gpt4 book ai didi

javascript - 从数组中获取ID,存储它并在本地删除它

转载 作者:行者123 更新时间:2023-12-03 06:26:56 25 4
gpt4 key购买 nike

我正在构建一个 Angular/Javascript/Ionic/Cordova 应用程序。

我有一个函数,我调用下面的数组,该数组存储为变量(existingEntries)

categories: Array [276]
[0...99]
0: Object
id: 288
exclude: false
1: Object
id: 320
exclude: true

此函数会抓取该数组中的所有元素,以查看排除值是否设置为 true 或 false

    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.. 函数,它可以工作,但是当我一遍又一遍地运行此代码时,我会得到重复项,并且我确信它可以编码得更好。我正在使用本地存储,因为我需要将数组保存在本地,但如果您有其他解决方案那就太好了。

    $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 而不是 false。

$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);
}

希望这是有道理的,并提前致谢!

最佳答案

您没有检查 existingEntries 数组中是否已存在条目,这就是您受到欺骗的原因 试试这个代码...

$scope.addLocalExcludedCategories = function(catID) {
console.log("addLocalExcludedCategories Called")
//Add Item to Excluded Categories Variable
var existingEntries = JSON.parse(window.localStorage.getItem("ExcludedCategories")) || [];

var entryId = catID;
var entry = {
'id': entryId,
};
if(existingEntries.length > 0){
existingEntries.forEach(function(entry){
if(entry.id !== entry.id){
existingEntries.push(entry);
}
});

关于javascript - 从数组中获取ID,存储它并在本地删除它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38607172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com