[英]delete individual items of the array in localStorage
我需要删除 localStorage 中整个数组的单个项目。 有没有可能做到这一点。 我尝试了下面的代码。 但它删除了整个监视列表。 我附上了本地存储元素的图像
function removeFromWatchlist(par) {
localStorage.removeItem("watchList")[par];
}
当然可以,但是您需要更新实际存储的值-在您的示例中,您要删除整个存储的数组。
然而,这将取决于par
到底是什么——因为你有一个对象数组,你必须决定equal
的含义。
例如。
function removeFromWatchlist(par) {
const list = localStorage.getItem('watchList');
const test = JSON.stringify(par);
localStorage.setItem('watchList', list.filter(x => JSON.stringify(x) === test));
}
这将从作为watchList
存储在本地存储中的数组中删除所有出现的par
。
要了解为什么这不起作用,您需要了解 JS 在从左到右解析这段代码时如何“读取”它:
localStorage.removeItem("watchList")
localStorage
的变量removeItem
"watchList"
从上述步骤调用 function[par]
这里的问题是,在第 3 步中,整个值从本地存储中删除,并且function removeItem
返回undefined
( https://developer.mozilla.org/en-US/docs/Web/API/Storage/removeItem#return_value ) .
要使其工作,您应该找到适合您任务的操作顺序:您想要修改本地存储中的值,因此您应该:
代码中的哪个看起来像
const value = localStorage.getItem("watchList") // step 1
const modified = /* write your logic here */ // step 2
localStorage.setItem("watchList", modified) // step 3
另外,不要忘记在 localStorage 中存储和获取的内容始终是字符串。 因此,如果您要存储对象,则应在使用getItem
读取对象时使用 JSON.parse( JSON.parse(value)
) 并在使用 setItem 存储对象时使用setItem
JSON.stringify(value)
。
removeItem()方法会在本地存储中删除 watchList 的所有项目,但是您可以找到要传递的 par 参数的索引并更新 watchList 数组并使用setItem()更新它。
const watchList = JSON.parse(localStorage.getItem('watchList')) || [];
const index = watchList.findIndex(item => item.imdbId === par.imbdId); // in your case imbdId is unique value
if(index !== -1) {
watchList.splice(index, 1); // removes the item from watchList based on the index
localStorage.setItem('watchList', JSON.stringify(watchList)); // updateing new watchList
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.