js实现自动售卖机
实现自动售卖机的基本逻辑
自动售卖机的核心功能包括商品展示、投币、选择商品、出货和找零。以下是一个简化的JavaScript实现示例。
商品库存管理
使用对象数组存储商品信息,包括名称、价格和库存数量:
const products = [
{ name: '可乐', price: 3, stock: 10 },
{ name: '雪碧', price: 3, stock: 8 },
{ name: '矿泉水', price: 2, stock: 15 }
];
投币系统
维护当前投入金额和总金额:
let currentAmount = 0;
let totalAmount = 0;
function insertCoin(amount) {
if (amount > 0) {
currentAmount += amount;
updateDisplay();
}
}
商品选择逻辑
检查余额和库存后出货:
function selectProduct(index) {
const product = products[index];
if (!product || product.stock <= 0) {
alert('商品已售罄');
return;
}
if (currentAmount >= product.price) {
product.stock--;
totalAmount += product.price;
currentAmount -= product.price;
dispenseProduct(product.name);
updateDisplay();
} else {
alert('金额不足');
}
}
出货和找零
function dispenseProduct(productName) {
console.log(`出货:${productName}`);
}
function returnChange() {
if (currentAmount > 0) {
console.log(`找零:${currentAmount}元`);
currentAmount = 0;
updateDisplay();
}
}
界面更新
function updateDisplay() {
document.getElementById('display').innerText =
`当前金额:${currentAmount}元 | 总收入:${totalAmount}元`;
}
HTML结构示例
<div id="display"></div>
<div id="products"></div>
<button onclick="insertCoin(1)">投1元</button>
<button onclick="insertCoin(5)">投5元</button>
<button onclick="returnChange()">退币</button>
初始化商品按钮
function initProducts() {
const container = document.getElementById('products');
products.forEach((product, index) => {
const btn = document.createElement('button');
btn.textContent = `${product.name} (${product.price}元)`;
btn.onclick = () => selectProduct(index);
container.appendChild(btn);
});
}
window.onload = initProducts;
扩展功能建议
- 添加管理员界面管理库存
- 实现硬币识别和纸币识别
- 添加交易记录功能
- 支持多种支付方式(扫码支付)
- 添加商品图片展示
这个实现包含了自动售卖机的基本功能,可以根据实际需求进一步扩展和完善。







