js实现atm
JavaScript实现ATM机功能
以下是一个简单的ATM机功能的JavaScript实现示例,包含基本的存款、取款、查询余额和转账功能。

class ATM {
constructor() {
this.balance = 0;
this.transactions = [];
}
deposit(amount) {
if (amount > 0) {
this.balance += amount;
this.transactions.push(`存款: +${amount}`);
return `存款成功,当前余额: ${this.balance}`;
}
return '存款金额必须大于0';
}
withdraw(amount) {
if (amount > 0) {
if (amount <= this.balance) {
this.balance -= amount;
this.transactions.push(`取款: -${amount}`);
return `取款成功,当前余额: ${this.balance}`;
}
return '余额不足';
}
return '取款金额必须大于0';
}
checkBalance() {
return `当前余额: ${this.balance}`;
}
transfer(amount, targetAccount) {
if (amount > 0) {
if (amount <= this.balance) {
this.balance -= amount;
targetAccount.balance += amount;
this.transactions.push(`转账: -${amount} 至 ${targetAccount.id}`);
targetAccount.transactions.push(`收款: +${amount} 来自 ${this.id}`);
return `转账成功,当前余额: ${this.balance}`;
}
return '余额不足';
}
return '转账金额必须大于0';
}
getTransactionHistory() {
return this.transactions;
}
}
使用示例
// 创建ATM实例
const myATM = new ATM();
// 存款
console.log(myATM.deposit(1000)); // 存款成功,当前余额: 1000
// 取款
console.log(myATM.withdraw(500)); // 取款成功,当前余额: 500
// 查询余额
console.log(myATM.checkBalance()); // 当前余额: 500
// 创建另一个账户用于转账
const anotherATM = new ATM();
anotherATM.id = 'ACCOUNT_002';
myATM.id = 'ACCOUNT_001';
// 转账
console.log(myATM.transfer(200, anotherATM)); // 转账成功,当前余额: 300
// 查看交易记录
console.log(myATM.getTransactionHistory());
// ["存款: +1000", "取款: -500", "转账: -200 至 ACCOUNT_002"]
功能扩展建议
- 添加用户认证功能,要求输入PIN码才能操作
- 实现账户类,存储用户信息
- 添加每日取款限额功能
- 实现数据库持久化,保存交易记录
- 添加账单打印功能
- 实现多币种支持
错误处理改进
class ATM {
// ...其他方法...
withdraw(amount) {
try {
if (amount <= 0) throw new Error('取款金额必须大于0');
if (amount > this.balance) throw new Error('余额不足');
this.balance -= amount;
this.transactions.push(`取款: -${amount}`);
return `取款成功,当前余额: ${this.balance}`;
} catch (error) {
return error.message;
}
}
}
这个实现提供了ATM的基本功能框架,可以根据实际需求进一步扩展和完善。






