首页 > 解决方案 > 如何从本地存储 JavaScript 中删除同一键的多个值中的单个选定值

问题描述

从 JavaScript 本地存储中具有多个值的键中删除单个值。

$("ul").on("click", "li", function() {
  $(this).remove();
  localStorage.removeItem();
});

let itemsArray = localStorage.getItem('items') 
                    ? JSON.parse(localStorage.getItem('items')) 
                    : [];

localStorage.setItem('items', JSON.stringify(itemsArray));
const data = JSON.parse(localStorage.getItem('items'));

标签: javascriptlocal-storage

解决方案


本地存储存储字符串。您的代码使用 JSON 来存储数组(作为字符串),这是一种常见且适当的方法。要从数组中仅删除一项,您:

  1. 从本地存储中获取 JSON
  2. 将 JSON 解析为数组
  3. 从数组中删除项目
  4. 获取更新后数组的 JSON
  5. 将其存储在本地存储中

通常我会在到达页面时执行第 1 步和第 2 步并保留结果。因此,我将对已有的结果执行第 3 步,然后将其放回存储中。你正在做类似的事情itemsArray,所以类似于:

$("ul").on("click", "li", function() {
  itemsArray = itemsArray.filter(entry => {
    return /*...code to determine whether to keep `entry`, should
           return true if `entry` isn't for this `li`, false if `entry`
           IS for this `li` */;
  });
  $(this).remove();
  localStorage.setItem("items", JSON.stringify(itemsArray));
});

推荐阅读