You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LocalStorage更新购物车数量出现数值拼接问题求代码排查

问题原因

你遇到的追加数量变为字符串拼接的问题确实是缺少数值类型转换导致的:HTML输入框的value属性取值默认是字符串类型,直接执行+=操作时会被识别为字符串拼接而非数值相加,就会出现「2+2=22」的异常结果。同时如果LocalStorage中之前存储的数量是字符串格式,JSON.parse读取后也会保留字符串类型,也可能触发拼接问题。

修复步骤

需要修改两处代码:

  • 获取输入的商品数量时,直接转为整数类型,可增加容错逻辑避免非数字输入导致NaN
  • 追加已有商品数量时,将本地存储中读取的原有数量也转为整数,避免历史存储的字符串类型导致异常

修改后完整代码

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);
  
    // 第一处修改:输入数量转整数,容错默认值为1
    let quantity = parseInt(productQuantity.value, 10) || 1;
    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 = parseInt(currentCart[itemIndex].quantity, 10) + productToAdd.quantity;
    } 
    
    else {
        currentCart.push(productToAdd);
    }

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

内容的提问来源于stack exchange,提问作者Stephen Warren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:06:04