本地存储更新数量

Local storage update quantities

我有一个问题 我已经制作了这段代码来更新我的本地存储,所以一切正常,但 当我更新本地存储以添加数量时,例如,如果我有 已经有 2 张沙发,我在本地存储中又添加了 2 张沙发,结果是 22

所以我认为它在我的代码中遗漏了一些“parseInt”,但我真的不知道在哪里 所以,如果你能帮助我,那就太好了,我真的不知道该怎么做

btnCart.addEventListener("click", (event)=>{


  event.preventDefault();

  function addToCart() {


    let color = colorChoice.value;
    console.log(color);
  
    let name = productName;
    console.log(name);
  
    let price = productPrice;
    console.log(price);
  
    let quantity = productQuantity.value;
    console.log(quantity);

  
    const productToAdd = {
      id : id,
      name : name,
      price : price,
      color: color,
      quantity: quantity
    };


    const currentCart = JSON.parse(localStorage.getItem(cartName)) ?? [];


    const itemIndex = currentCart.findIndex((item) =>
            item.id === productToAdd.id && item.color === productToAdd.color
    );

    if (itemIndex !== -1) {

        currentCart[itemIndex].quantity += productToAdd.quantity;
    } 
    
    else {
    
        currentCart.push(productToAdd);
    }


    localStorage.setItem(cartName, JSON.stringify(currentCart));
}
addToCart();


})

LocalStorage return 字符串,所以你不能这样做:

currentCart[itemIndex].quantity += productToAdd.quantity;

您需要解析 localStorage 值例如:

const qty = parseInt(currentCart[itemIndex].quantity);
currentCart[itemIndex].quantity = qty + productToAdd.quantity;