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

JavaScript购物车数组处理:点击加购时更新已有商品数量

购物车商品添加逻辑实现

现有数据

初始购物车数组与待添加商品对象如下:

let cartData = [];
const item = {
  product_name: "ProductName1",
  product_image_url: "imageURL1",
  price: "28",
  qty: 1
};

核心需求

点击「加入购物车」按钮时,需实现以下逻辑:

  • 若目标商品已在购物车中,仅更新该商品的qty字段(累加当前待添加商品的数量)
  • 若目标商品不在购物车中,直接将该商品对象追加到购物车数组内

预期输出

场景1:重复添加同一商品

执行添加操作后,购物车数组应更新为:

cartData = [{
  product_name: "ProductName1",
  product_image_url: "imageURL1",
  price: "28",
  qty: 2
}]

场景2:添加全新商品

当传入新的商品对象时,购物车数组应更新为:

cartData = [{
  product_name: "ProductName1",
  product_image_url: "imageURL1",
  price: "28",
  qty: 1
}, {
  product_name: "ProductName2",
  product_image_url: "imageURL2",
  price: "38",
  qty: 1
}]

实现方案

以product_name作为商品唯一标识,通过findIndex方法快速定位商品,再执行对应逻辑:

function addToCart(cart, item) {
  const existingItemIndex = cart.findIndex(cartItem => cartItem.product_name === item.product_name);
  
  if (existingItemIndex !== -1) {
    // 商品已存在,累加数量
    cart[existingItemIndex].qty += item.qty;
  } else {
    // 商品不存在,浅拷贝后添加到购物车(避免原对象后续修改影响购物车数据)
    cart.push({...item});
  }
}

// 使用示例
// 场景1测试
addToCart(cartData, item);
console.log(cartData); // 输出场景1的预期结果

// 场景2测试
const newItem = {
  product_name: "ProductName2",
  product_image_url: "imageURL2",
  price: "38",
  qty: 1
};
addToCart(cartData, newItem);
console.log(cartData); // 输出场景2的预期结果

内容的提问来源于stack exchange,提问作者Ramnath Rajendran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:07:25