js使用class类写一个购物车案例
时间: 2024-05-13 13:13:52 浏览: 9
好的,以下是使用class类写的购物车案例:
```
class ShoppingCart {
constructor() {
this.items = [];
}
addItem(itemName, quantity, price) {
const item = {
name: itemName,
quantity: quantity,
price: price
};
this.items.push(item);
}
removeItem(itemName) {
this.items = this.items.filter(item => item.name !== itemName);
}
getTotalPrice() {
return this.items.reduce((total, item) => {
return total + (item.quantity * item.price);
}, 0);
}
getItemCount() {
return this.items.reduce((total, item) => {
return total + item.quantity;
}, 0);
}
}
// 创建购物车实例
const myCart = new ShoppingCart();
// 添加商品
myCart.addItem('水果', 2, 10);
myCart.addItem('蔬菜', 3, 5);
// 获取购物车商品数量和总价
console.log(myCart.getItemCount()); // 输出:5
console.log(myCart.getTotalPrice()); // 输出:40
// 删除商品
myCart.removeItem('蔬菜');
// 再次获取购物车商品数量和总价
console.log(myCart.getItemCount()); // 输出:2
console.log(myCart.getTotalPrice()); // 输出:20
```
这个购物车类包含了添加商品、删除商品、获取商品数量和获取总价等功能。可以根据需要进行扩展。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)