自动售货系统(web)

本文介绍了如何用JavaScript构建一个基础的自动售货系统,包括列出商品信息、补货操作和销售验证,展示了商品的名称、价格和库存管理。
摘要由CSDN通过智能技术生成

1、做一个简易的自动售货系统,售货柜中有若干种商品,每种商品有名称(name)、价格(price)、 库存(stock) 三个属性。实现以下功能。

  1. 售货柜可以列出当前的所有商品,每种商品显示各自的名称、库存和价格。
  2. 给售货柜补货,即给指定名称的商品添加一定数量的库存。
  3. 销售商品,给定商品的名称和数量以及顾客预支配金额,判断金额是否足够,若不够则进行提醒,若足够则减库存并找零。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>售货柜</title>
</head>
<script>
    let Product = function (name, price, stock) {
      this.name = name;
      this.price = price;
      this.stock = stock;
      this.addStock = function(quantity) {
        this.stock += quantity;
      }
      this.show = function(){
        console.log(`${this.name}, ${this.price}元, ${this.stock}件`);
      }
    }
    
    let SellingMachine = function () {
      this.products = [
          new Product('Coca Cola',3,10),
          new Product('honey',27,17),
          new Product('herb juice',6,12)
      ];
      this.list = function() {
        console.log(`销售以下商品:`);
        this.products.forEach(m => m.show());
      }
      this.replenishment = function(name, quantity){
        if (quantity <= 0) {
          throw new Error('quantity必须大于0');
        }
        const product = this.products.find(x => x.name == name);
        if (product === undefined) {
          console.log(`不销售${name}`);
          return;
        }
        product.addStock(quantity);
        console.log(`补货成功,${product.name}剩余${product.stock}件`);
      }
      this.sell = function(name, quantity, money) {
        const product = this.products.find(x => x.name == name);
        if (product === undefined) {
          console.log(`不销售${name}`);
          return;
        }
    
        if (product.stock < quantity) {
          console.log(`库存不足,${product.name} 仅剩 ${product.stock} 件`);
          return;
        }
    
        const totalPrice = quantity * product.price;
        if (money < totalPrice) {
          console.log(`金额不足,${name} ${quantity}件应付¥${totalPrice}`);
          return;
        }
    
        product.addStock(-quantity);
        const rest = money - totalPrice;
        console.log(`成功购买商品:${name}, ${quantity}件, 共${totalPrice}元,请取走您的商品。${rest>0?`以及零钱${rest}元。`:''}`);
        return rest;
      }
    }
    
    const machine = new SellingMachine();
    machine.list();
    machine.sell('西瓜');
    machine.sell('herb juice',6,12);
    machine.replenishment('herb juice', 20);
    machine.list();
    
</script>
<body>
</body>
</html>

  • 16
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值