本文最后更新于 535 天前,其中的信息可能已经有所发展或是发生改变。
介绍
效果
解题思路
可能写的复杂了些,总体思路是遍历出购物车数组中是否已经添加,若已经添加,则对应商品数量++即可,反之亦然,删除时调用arr.splice(idx,1)删除对应元素即可.
addToCart(goods) {
// TODO:修改当前函数,实现购物车加入商品需求
for (const idx in this.cartList) {
if (goods.id === this.cartList[idx].id) {
this.cartList[idx].num++;
return;
}
}
goods.num = 1;
this.cartList.push(goods);
this.cartList = JSON.parse(JSON.stringify(this.cartList));
},
removeGoods(goods) {
// TODO:补全代码实现需求
for (const idx in this.cartList) {
if (goods.id === this.cartList[idx].id) {
if (this.cartList[idx].num >= 2) this.cartList[idx].num--;
else this.cartList.splice(idx, 1);
return;
}
}
}