gpt4 book ai didi

javascript - 无法删除 localStorage 数组项

转载 作者:行者123 更新时间:2023-12-04 07:56:57 26 4
gpt4 key购买 nike

我正在尝试从保存在 localStroage 中的购物车中删除单个购物车项目,到目前为止我只能通过 removeitem() 或 clear() 删除整个数组,但我想按项目 ID 删除选择性项目。意思是,如果我使用 splice,则会出现低于错误的情况。我正在学习,所以如果我需要提供更多信息,请告诉我。

deleteProduct: (index) => {
const existingEntries = JSON.parse(localStorage.getItem("cartData"));
existingEntries.splice(index, 1);
localStorage.setItem("cartData", JSON.stringify(existingEntries));
}
let cartData = window.localStorage.getItem('cartData');

const cart = {
state: {
cartData: cartData ? JSON.parse(cartData) : {
foods: [],
totalPrice: [],
Quantities: []
},
},

enter image description here
enter image description here

最佳答案

笔记:

  • 购物车数据是 String ,它在 localStorage ,所以它一定是 String .
  • 解析,是Object
  • cartData.foods是这里的数组

  • 代码步骤:
  • 获取 cartData来自 localStorage
  • 解析它,你会得到一个 JSON Object有 key .food
  • 访问 key ,cartData.foods
  • 拼接
  • 关于javascript - 无法删除 localStorage 数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66652986/

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