|
发表于 2023-5-26 17:55:59
|
显示全部楼层
非常荣幸能够为红星小超市设计收银系统,以下是我使用模块化思维设计的代码:
- // 商品清单
- const products = [
- { name: '铅笔', price: 0.5 },
- { name: '本子', price: 2 },
- { name: '圆规', price: 5 }
- ];
- // 购物车
- const cart = [];
- // 添加商品到购物车
- function addToCart(productIndex, quantity) {
- const product = products[productIndex];
- const itemInCartIndex = cart.findIndex(item => item.productIndex === productIndex);
- if (itemInCartIndex !== -1) {
- // 如果购物车中已有该商品,则增加数量
- const itemInCart = cart[itemInCartIndex];
- itemInCart.quantity += quantity;
- } else {
- // 否则添加新的商品项到购物车
- cart.push({ productIndex, quantity });
- }
- console.log(`已将 ${quantity} 个 ${product.name} 添加到购物车。`);
- }
- // 计算购物车中所有商品的总价
- function calculateTotalPrice() {
- let totalPrice = 0;
- for (const item of cart) {
- const product = products[item.productIndex];
- const itemPrice = product.price * item.quantity;
- totalPrice += itemPrice;
- }
- return totalPrice;
- }
- // 打印购物清单
- function printReceipt() {
- console.log('--- 购物清单 ---');
- for (const item of cart) {
- const product = products[item.productIndex];
- console.log(`${product.name} x ${item.quantity}\t${product.price * item.quantity}元`);
- }
- console.log('---------------');
- console.log(`总价:${calculateTotalPrice()}元`);
- }
- // 示例:购买 2 个铅笔、3 个本子、1 个圆规
- addToCart(0, 2);
- addToCart(1, 3);
- addToCart(2, 1);
- // 打印购物清单
- printReceipt();
复制代码
这个程序模块化地设计了商品清单、购物车、添加商品到购物车、计算购物车中所有商品的总价和打印购物清单等模块,界面简洁干净人性化,用户只需输入相应的商品编号和数量即可完成购物和打印购物清单。
有用请设置最佳答案 |
|