当前位置:首页 > 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实现乘

JavaScript 实现乘法运算 在 JavaScript 中实现乘法运算可以通过多种方式完成,包括基本运算符、函数封装以及高级算法(如大数乘法)。以下是几种常见方法: 使用基本乘法运算符 Jav…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数:…

js实现文字滚动

js实现文字滚动

实现文字滚动的几种方法 使用CSS动画实现滚动 通过CSS的@keyframes和transform属性可以实现平滑的文字滚动效果。 <style> .scroll-text { w…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…

js实现下拉刷新

js实现下拉刷新

监听触摸事件 通过监听 touchstart、touchmove 和 touchend 事件来检测用户下拉手势。记录触摸起始位置和移动距离。 let startY = 0; let curr…