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

如何更新对象数组中的对象?购物车商品数量增量实现

解决购物车重复添加商品问题:仅增量更新数量

我有一个存储商品的对象数组,需要随机选取商品添加至购物车并存储到localStorage中。目前添加已存在的商品时会创建重复对象,希望改为仅增量更新该商品的quantity属性。原实现代码如下:

var cart = [];
var products = [
  {
    id: 1,
    productDescription: "Iphone 14 pro",
    price: 1544,
    quantity: 1
  },
  {
    id: 2,
    productDescription: "OPPOF19",
    price: 788,
    quantity: 1
  },
  {
    id: 3,
    productDescription: "Microsoft Surface Laptop 4",
    price: 2500,
    quantity: 1
  },
  {
    id: 4,
    productDescription: "Fog Scent Xpressio Perfume",
    price: 15,
    quantity: 1
  },
  {
    id: 5,
    productDescription: "Hyaluronic Acid Serum",
    price: 19,
    quantity: 1
  }
];

var item = products[Math.floor(Math.random() * products.length)];
if (localStorage.getItem('ItemsInCart')) {
  var previousCartItems = localStorage.getItem("ItemsInCart");
  cart = JSON.parse(previousCartItems);
  let obj = cart.some((o, i) => {
    if (o.id == item.id) {
      cart[i].quantity = cart[i].quantity + 1;
      localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
      return true;
    } else {
      item.quantity = 1;
      cart.push(item);
      localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
      return true;
    }
  });
} else {
  item.quantity = 1;
  cart.push(item);
  localStorage.setItem("ItemsInCart", (JSON.stringify(cart)));
}
console.log('*******************')
console.log(cart)
console.log('*******************')

原代码问题分析

  1. Array.some()用法错误:some方法只要找到一个匹配项就会停止遍历,但原代码中每遇到不匹配的商品就直接执行添加操作,导致第一个不匹配的项就会触发商品添加,完全没有检查完整购物车列表。
  2. 直接操作原商品对象:对象是引用类型,直接push原数组中的商品对象,会导致修改购物车数量时同步改动原products数组里的对应商品。
  3. 重复写入localStorage:在遍历过程中多次执行存储操作,既没必要也影响性能。

修正后的代码

var cart = [];
var products = [
  { id: 1, productDescription: "Iphone 14 pro", price: 1544, quantity: 1 },
  { id: 2, productDescription: "OPPOF19", price: 788, quantity: 1 },
  { id: 3, productDescription: "Microsoft Surface Laptop 4", price: 2500, quantity: 1 },
  { id: 4, productDescription: "Fog Scent Xpressio Perfume", price: 15, quantity: 1 },
  { id: 5, productDescription: "Hyaluronic Acid Serum", price: 19, quantity: 1 }
];

// 随机选中商品并创建副本,避免修改原数组对象
var selectedItem = { ...products[Math.floor(Math.random() * products.length)] };

// 从localStorage读取已有购物车数据
if (localStorage.getItem('ItemsInCart')) {
  cart = JSON.parse(localStorage.getItem("ItemsInCart"));
}

// 查找购物车中是否存在当前商品
const existingItemIndex = cart.findIndex(item => item.id === selectedItem.id);

if (existingItemIndex !== -1) {
  // 商品已存在,增量更新数量
  cart[existingItemIndex].quantity += 1;
} else {
  // 商品不存在,添加新商品并设置数量为1
  selectedItem.quantity = 1;
  cart.push(selectedItem);
}

// 统一将更新后的购物车存入localStorage
localStorage.setItem("ItemsInCart", JSON.stringify(cart));

console.log('*******************');
console.log(cart);
console.log('*******************');

关键修改说明

  • 使用findIndex()替代some():精准定位购物车中已存在的商品索引,逻辑更清晰可靠。
  • 创建商品副本:通过扩展运算符{ ...item }复制选中的商品,避免修改原products数组的对象引用。
  • 统一存储操作:所有购物车逻辑处理完成后,仅执行一次localStorage写入,提升性能。
  • 拆分逻辑步骤:先读取购物车、再检查商品状态、最后统一保存,代码结构更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:13:10