js实现自动售卖机
实现自动售卖机的核心逻辑
自动售卖机的JavaScript实现需要模拟商品选择、投币、找零、库存管理等核心功能。以下是一个基础实现框架:

class VendingMachine {
constructor() {
this.products = {
'A1': { name: '可乐', price: 3, stock: 5 },
'A2': { name: '雪碧', price: 3, stock: 5 },
'B1': { name: '矿泉水', price: 2, stock: 10 }
};
this.balance = 0;
this.coins = [1, 2, 5]; // 支持的硬币面额
}
insertCoin(amount) {
if (!this.coins.includes(amount)) {
throw new Error('不支持该面额');
}
this.balance += amount;
return this.balance;
}
selectProduct(code) {
const product = this.products[code];
if (!product) throw new Error('无效商品代码');
if (product.stock <= 0) throw new Error('商品已售罄');
if (this.balance < product.price) throw new Error('余额不足');
product.stock--;
const change = this.balance - product.price;
this.balance = 0;
return { product, change };
}
}
界面交互实现
结合HTML创建基础交互界面:

<div id="vending-machine">
<div class="display">余额: ¥<span id="balance">0</span></div>
<div class="products">
<div class="product" data-code="A1" data-price="3">
<span>A1 - 可乐</span>
<span>¥3</span>
</div>
<!-- 其他商品... -->
</div>
<div class="coin-buttons">
<button data-amount="1">¥1</button>
<button data-amount="2">¥2</button>
<button data-amount="5">¥5</button>
</div>
</div>
const machine = new VendingMachine();
const balanceDisplay = document.getElementById('balance');
document.querySelectorAll('.coin-buttons button').forEach(button => {
button.addEventListener('click', () => {
const amount = parseInt(button.dataset.amount);
machine.insertCoin(amount);
balanceDisplay.textContent = machine.balance;
});
});
document.querySelectorAll('.product').forEach(product => {
product.addEventListener('click', () => {
try {
const result = machine.selectProduct(product.dataset.code);
alert(`已购买 ${result.product.name}, 找零 ¥${result.change}`);
balanceDisplay.textContent = '0';
} catch (error) {
alert(error.message);
}
});
});
库存管理扩展
添加库存管理方法:
class VendingMachine {
// ...原有代码...
restock(code, quantity) {
if (!this.products[code]) throw new Error('无效商品代码');
this.products[code].stock += quantity;
}
getInventory() {
return Object.entries(this.products).map(([code, item]) => ({
code,
...item
}));
}
}
交易记录功能
添加交易历史记录:
class VendingMachine {
constructor() {
// ...原有属性...
this.transactions = [];
}
selectProduct(code) {
// ...原有逻辑...
this.transactions.push({
product: code,
amount: product.price,
timestamp: new Date()
});
return { product, change };
}
getTransactionHistory() {
return [...this.transactions];
}
}
测试用例示例
const testMachine = new VendingMachine();
testMachine.insertCoin(5);
const result = testMachine.selectProduct('A1');
console.log(result); // 应输出购买结果和找零2元
console.log(testMachine.getInventory()); // 检查库存变化
实现时可根据实际需求扩展功能,如支持纸币、网络支付、温度控制等功能。核心在于维护好状态管理(余额、库存)和正确处理各种边界情况(库存不足、余额不足等)。






