当前位置:首页 > JavaScript

js实现atm

2026-03-13 20:05:48JavaScript

JavaScript实现ATM机功能

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

js实现atm

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"]

功能扩展建议

  1. 添加用户认证功能,要求输入PIN码才能操作
  2. 实现账户类,存储用户信息
  3. 添加每日取款限额功能
  4. 实现数据库持久化,保存交易记录
  5. 添加账单打印功能
  6. 实现多币种支持

错误处理改进

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的基本功能框架,可以根据实际需求进一步扩展和完善。

标签: jsatm
分享给朋友:

相关文章

js实现验证码

js实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas i…

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现变形

js实现变形

使用 CSS 和 JavaScript 实现元素变形 在 JavaScript 中实现变形效果通常结合 CSS 的 transform 属性,通过动态修改该属性实现元素的旋转、缩放、倾斜或平移。 基…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…

js实现上传文件

js实现上传文件

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。 <input type="file"…