所有,这是我在这里的第一个问题,所以我希望我的措辞正确并提供足够的信息以供使用。
我在本地存储中有一个名为 faveGifs 的键,其中存储了多个项目,每个项目都是一个对象。我希望能够单独删除这些对象。到目前为止,我可以删除第一个对象,即位置 0 的对象。我希望能够在它们所在的任何索引处删除它们,例如位置 2。我知道我必须获得每个对象的索引才能实现此目的,但是,当我通过 indexOf() 运行 key 时,我获得的唯一索引是 -1。
这是我的本地存储 key 的样子:
faveGifs[
{id: 'jijijoj',rating: 'g'},
{id: 'iojiojoi',rating: 'r'},
{id: 'eawfe',rating: 'pg'},
{id: 'ewfewfwe',rating: 'g'},
{id: 'ewfewfew',rating: 'r'}
];
这是我的代码:
$(document).on("click", "#remove", function () {
let faveGifs = JSON.parse(localStorage.getItem("faveGifs"));
let faveGif = faveGifs.map(faveGif => faveGif.id);
//Neither of the following has worked for me:
//let index = faveGif.indexOf(faveGif);
//let index = faveGif.indexOf(faveGifs);
console.log(index);
// faveGifs.splice(index, 1);
// localStorage.setItem("faveGifs", JSON.stringify(faveGifs));
// populateFaves();
});
我尝试过使用类似问题的解决方案,但没有一个对我有用。我试过的有:
Remove a specific item from localstorage with js
Remove json object in localstorage using js
How do I remove an object from an array with JavaScript?
还有其他几个,但就像我说的,没有一个对我有用。
非常感谢所有帮助过我的人。
最佳答案
问题是 faveGif
仍然是一个数组 - 它看起来像这样:
faveGif = ['jijijoj', 'iojiojoi', 'eawfe', 'ewfewfwe', 'ewfewfew'];
所以如果你想找到某个 ID 的索引(比方说 ewfewfew
):
let index = faveGif.findIndex(id => id == "ewfewfew");
这与 faveGifs
中的索引相同,因此它会为您提供所需的结果。
演示:
let faveGifs = [{
id: 'jijijoj',
rating: 'g'
}, {
id: 'iojiojoi',
rating: 'r'
}, {
id: 'eawfe',
rating: 'pg'
}, {
id: 'ewfewfwe',
rating: 'g'
}, {
id: 'ewfewfew',
rating: 'r'
}];
let faveGif = faveGifs.map(faveGif => faveGif.id);
let index = faveGif.findIndex(id => id == "ewfewfew");
console.log(index); //Should return 4
关于javascript - 尝试获取 localstorage 中的对象索引,以便我可以使用 javascript 或 jquery 从 localStorage 存储中删除/删除该对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55035754/