js实现atm


JavaScript实现ATM机功能
以下是一个简单的JavaScript实现ATM机功能的代码示例,包含基本的存款、取款、查询余额和退出功能。
初始化变量
let balance = 1000; // 初始余额
const pin = '1234'; // 预设PIN码
let attempts = 3; // 密码尝试次数
验证PIN码
function verifyPin(inputPin) {
if (inputPin === pin) {
return true;
} else {
attempts--;
return false;
}
}
存款功能
function deposit(amount) {
if (amount > 0) {
balance += amount;
return `存款成功,当前余额: ${balance}`;
} else {
return '存款金额必须大于0';
}
}
取款功能
function withdraw(amount) {
if (amount > balance) {
return '余额不足';
} else if (amount <= 0) {
return '取款金额必须大于0';
} else {
balance -= amount;
return `取款成功,当前余额: ${balance}`;
}
}
查询余额
function checkBalance() {
return `当前余额: ${balance}`;
}
主菜单
function atmMenu() {
let choice;
do {
choice = prompt(`
ATM菜单:
1. 查询余额
2. 存款
3. 取款
4. 退出
请选择操作(1-4):
`);
switch(choice) {
case '1':
alert(checkBalance());
break;
case '2':
const depositAmount = parseFloat(prompt('请输入存款金额:'));
alert(deposit(depositAmount));
break;
case '3':
const withdrawAmount = parseFloat(prompt('请输入取款金额:'));
alert(withdraw(withdrawAmount));
break;
case '4':
alert('感谢使用,再见!');
break;
default:
alert('无效选择,请重新输入');
}
} while (choice !== '4');
}
启动ATM
function startATM() {
let inputPin;
while (attempts > 0) {
inputPin = prompt('请输入您的PIN码:');
if (verifyPin(inputPin)) {
atmMenu();
break;
} else {
alert(`PIN码错误,剩余尝试次数: ${attempts}`);
}
}
if (attempts === 0) {
alert('尝试次数过多,卡已被锁定');
}
}
// 启动ATM
startATM();
功能扩展建议
- 添加交易记录功能,记录每笔交易的时间和金额
- 实现转账功能,允许向其他账户转账
- 添加修改PIN码的功能
- 实现账户锁定和解锁机制
- 添加图形用户界面(GUI)而非使用prompt/alert
这个简单的ATM实现可以在浏览器控制台中运行,或者嵌入到HTML页面中使用。根据需求可以进一步扩展功能和完善用户体验。






