【问题标题】:How do I remove an object in my array that was saved using local storage?如何删除数组中使用本地存储保存的对象?
【发布时间】:2019-03-30 23:55:31
【问题描述】:

我正在制作一个基本的购物车,它使用点击事件处理程序将对象推送到数组中。我设法做到了这一点,并使用本地存储将对象保存在数组中。我想知道的是我现在如何从数组中删除一个对象?当我使用 pop() 并刷新页面时,对象仍在我的数组中。当我使用 localStorage.removeItem() 时,它最终会擦除数组中的所有对象。

我尝试了 localStorage.removeItem,但它从我的数组中删除了所有对象。

这是我的一些代码:

// Add to cart
var cart =  JSON.parse(localStorage.getItem('cart')) || [];

var product1 = {
    name: "product1",
    price: 90.00
};

document.getElementById("cart-button").addEventListener("click", addToCart);

function addToCart() {
    cart.push(product1.name + "<br />" + product1.price);
    localStorage.setItem('cart', JSON.stringify(cart));
    document.getElementById("cart-contents").innerHTML = cart;
}

// Remove an item from the cart
document.getElementById("remove-button").addEventListener("click", removeItem);

function removeItem() {
    removeItem(product1);
    cart.pop();
    document.getElementById("cart-contents").innerHTML = cart;
}

【问题讨论】:

标签: javascript html arrays local-storage


【解决方案1】:
// Add to cart
      var cart = JSON.parse(localStorage.getItem('cart')) || [];

      var product1 = {
        name: 'product1',
        price: 90.0
      };

      document
        .getElementById('cart-button')
        .addEventListener('click', addToCart);

      function addToCart() {
        cart.push(product1.name + '<br />' + product1.price);
        localStorage.setItem('cart', JSON.stringify(cart));
        document.getElementById('cart-contents').innerHTML = cart;
      }

      // Remove an item from the cart
      document
        .getElementById('remove-button')
        .addEventListener('click', removeItem);

      function removeItem() {
        cart.pop();
        localStorage.setItem('cart', JSON.stringify(cart));
        document.getElementById('cart-contents').innerHTML = cart;
      }

你的错误是removeItem(product1);

【讨论】:

  • 当我移除 removeItem(product1);行,当我刷新页面并单击页面上的添加到购物车时,它仍然具有数组中的对象。
  • 抱歉没注意,现在添加修复
猜你喜欢
  • 2019-05-16
  • 2021-09-22
  • 1970-01-01
  • 2013-04-16
  • 2023-03-14
  • 2020-06-13
  • 2017-03-03
  • 2018-01-25
  • 2021-09-02
相关资源
最近更新 更多