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
相关产品推荐
相关产品推荐

