【问题标题】:How to update localstorage object value from index and key如何从索引和键更新本地存储对象值
【发布时间】:2019-07-24 18:41:56
【问题描述】:

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

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

举例

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

【问题讨论】:

  • 你没有正确使用localStorage
  • 这不是您获取或设置为 localStorage 的方式。请通过Window.localStorage。 localStorage 使用字符串键值对。您如何将 cart 设置为 localStorage?
  • @jeto 真相是什么?
  • 看这里:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage。请特别注意检索值的方式(使用.getItem)以及注意:键和值始终是字符串。您需要对数组进行字符串化并在检索时对其进行解析。
  • 我想他现在已经知道文档的 URL 了,伙计们 :)

标签: javascript arrays object local-storage


【解决方案1】:

localStorage不能存储复杂对象,只能以string存储数据。

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

window.localStorage.setItem('cart', JSON.stringify(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));

        } 

【讨论】:

    【解决方案2】:

    它对我有用 @PSK 感谢您的努力 @adiga 我想我犯了一个逻辑错误。也感谢您的关注!

    【讨论】:

      猜你喜欢
      • 2020-07-07
      • 1970-01-01
      • 2018-02-18
      • 2014-06-05
      • 2018-11-04
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多