map实现购物车的增删改查
一、业务需求
通过调用购物车中的增删改方法,实现对删除的增删改查,使用map的一些方法来进行实现
二、代码应用
设计思路:使用类对购物车进行封装,将增删改查作为购物车的一个原型方法,在静态属性constructor中new一个map实例用来作为购物车。
购物车使用map集合,一种商品对应一种数量
1.添加商品时,可以先判断购物车中是否含有该商品,如果有,则只需要在原数量的基础上增加数量。如果没有,则直接将商品放入购物车
2.删除商品,同上
3.清空商品
4.计算商品的总价,计算商品的总价需要获取商品的数量以及商品的单价,可以使用for…of循环,对购物车中每一个商品进行一个遍历,获取商品的数量以及单价
class Goods { constructor(id, name, price) { this.id = id; this.name = name; this.price = price; } } let fbm = new Goods(1, 北京方便面, 2); let kqs = new Goods(2, 怡宝矿泉水, 2.5) class Shopcar { car; constructor() { //<Goods,number> this.car = new Map(); } // 向购物车中添加商品 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] of this.car) { money += (goods.price) * num; } return money; }; //查看购物车 list() { for (let item of this.car) { console.log(item); } } } // 为用户分配购物车 let shopCar = new Shopcar(); // 用户购买商品 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());
上一篇:
IDEA上Java项目控制台中文乱码