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

map函数中if else条件判断失效 购物车添加商品逻辑异常

问题根源

  • 错误使用map方法做遍历判断:map本质是用于生成新数组的方法,仅做逻辑遍历校验使用find/some/forEach更适配
  • 嵌套循环逻辑存在漏洞:遍历购物车数组时,只要遇到任意一个ID不匹配的商品,就会触发新增逻辑。例如购物车已存在ID为1、2的商品,再次添加ID为1的商品时,遍历到ID为2的商品就会进入else分支,重复推入ID为1的商品
  • 未统一前置判断目标商品是否已在购物车中,多层嵌套循环导致逻辑混乱

修复后代码

addToCart(itemtoAdd) {
  // 查找对应库存商品
  const stockItem = this.itemList.find(item => item.id === itemtoAdd.id)
  // 库存不存在/库存不足直接终止逻辑
  if (!stockItem || stockItem.quantity <= 0) return

  // 校验商品是否已在购物车中
  const isExistInCart = this.shopcart.some(shopitem => shopitem.id === itemtoAdd.id)

  // 扣减库存、增加购物车计数
  stockItem.quantity -= 1
  this.cartCount += 1

  // 仅当商品未在购物车中时才推入数组
  if (!isExistInCart) {
    this.shopcart.push(itemtoAdd)
  }
  console.log(this.shopcart)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:36:06