javascript - 如何从索引和键更新本地存储对象值

标签 javascript arrays object local-storage

我的项目需要这个解决方案。这对我来说非常重要。 我想用键和索引从本地存储更新对象值 为了 我的购物车应用程序。

(购物车中产品数量的减少按钮)

示例。

function decreaseQuantity(index) {
  var oldQty = localStorage.cart[index].quantity;
  var newQty = oldQty - 1;
  localStorage.setItem(cart[index].quantity, newQty);
}

最佳答案

您不能在localStorage 中存储复杂的对象,您只能将数据存储为string

如果您想将购物车对象存储到 locaStorage 中,您需要使用 JSON.stringify 将其序列化为字符串并按如下方式存储。

window.localStorage.setItem('cart', JSON.stringify(cart));

注意:这里'cart'是关键。

要返回,更改它并存储回来,你需要像下面那样做。

 var data = window.localStorage.getItem('cart');
        if (data != null) {
            let cart= JSON.parse(data);
              cart[index].quantity = cart[index].quantity -1;
             window.localStorage.setItem('cart', JSON.stringify(cart));

        } 

关于javascript - 如何从索引和键更新本地存储对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966531/

相关文章:

javascript - 数据集属性不适用于对象?

javascript - 如何在 Electron 应用程序中使用音乐元数据摆脱引用错误

javascript - 如何解决 Vue 3 自定义渲染器错误

PHP/Javascript : Variable Swapping & Function calling

javascript - 如何在javascript中获取json数组中的重复对象

javascript - 为什么我的 8 拼图解决方案在我创建两次数组时运行得更快

C++创建没有默认构造函数的对象数组

javascript - 替换 javascript 中两个数组中出现的项目

c++ - 常量数组

Java - 非静态类的扩展静态类