map实现购物车的增删改查

2022-06-27 14:45:39

一、业务需求

通过调用购物车中的增删改方法,实现对删除的增删改查,使用map的一些方法来进行实现

二、代码应用

设计思路:使用类对购物车进行封装,将增删改查作为购物车的一个原型方法,在静态属性constructor中new一个map实例用来作为购物车。

购物车使用map集合,一种商品对应一种数量

1.添加商品时,可以先判断购物车中是否含有该商品,如果有,则只需要在原数量的基础上增加数量。如果没有,则直接将商品放入购物车

2.删除商品,同上

3.清空商品

4.计算商品的总价,计算商品的总价需要获取商品的数量以及商品的单价,可以使用for…of循环,对购物车中每一个商品进行一个遍历,获取商品的数量以及单价

classGoods{constructor(id, name, price){this.id= id;this.name= name;this.price= price;}}let fbm=newGoods(1,'北京方便面',2);let kqs=newGoods(2,'怡宝矿泉水',2.5)classShopcar{

    car;constructor(){//<Goods,number>this.car=newMap();}// 向购物车中添加商品add(goods, num){if(this.car.has(goods)){let n=this.car.get(goods);this.car.set(goods, n+ num);}else{this.car.set(goods, num);}}// 向购物车中移出商品remove(goods){this.car.delete(goods);}// 从购物车中改变商品的数量edit(goods, num){if(this.car.has(goods)){this.car.set(goods, num);}else{}}// 从购物车中清空clear(){this.car.clear();}// 结算sum(){let money=0;for(let[goods, num]ofthis.car){
            money+=(goods.price)* num;}return money;};//查看购物车list(){for(let itemofthis.car){
            console.log(item);}}}// 为用户分配购物车let shopCar=newShopcar();// 用户购买商品
shopCar.add(fbm,1);
shopCar.add(fbm,1);
shopCar.add(kqs,1);
shopCar.list();// 从购物车中移出商品
shopCar.remove(fbm);
shopCar.list();// shopCar.edit(fbm, 5);

console.log(shopCar.sum());
  • 作者:不想有bug的小菜鸟
  • 原文链接:https://blog.csdn.net/qq_45030966/article/details/120442179
    更新时间:2022-06-27 14:45:39