Javascript 如何从本地存储中删除同一密钥的多个值中的单个选定值

Javascript 如何从本地存储中删除同一密钥的多个值中的单个选定值,javascript,local-storage,Javascript,Local Storage,从JavaScript本地存储中具有多个值的键中删除单个值 $("ul").on("click", "li", function() { $(this).remove(); localStorage.removeItem(); }); let itemsArray = localStorage.getItem('items') ? JSON.parse(localStorage.getItem('items'))

从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'));

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

  • 从本地存储获取JSON
  • 将JSON解析为数组
  • 从数组中删除该项
  • 获取更新数组的JSON
  • 将其存储在本地存储中
  • 通常,我在到达页面时执行步骤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));
    });
    

    提供您的HTML和示例localstorage数据您存储的是对象还是数组?我使用的是数组。