下面是一段纯 JavaScript 代码,无需任何 HTML,直接在浏览器控制台或 Node.js 中运行即可看到完整的银行模拟效果。
javascript
// ============================================================
// 工商银行模拟器 · 纯 JS 演示
// 无需 HTML,运行即可体验存取款、转账、查询余额
// ============================================================
class ICBCBankSimulator {
constructor(initialBalance = 10000) {
// 账户核心数据
this.account = {
bankName: '中国工商银行',
cardNumber: this._generateCardNumber(),
holder: '张三',
balance: initialBalance,
currency: 'CNY',
};
// 交易日志
this.transactions = [];
// 初始化时记录一条开户日志
this._log('开户', `初始余额 ¥${initialBalance.toFixed(2)}`);
}
// ----------------------------------------------------------
// 私有工具方法
// ----------------------------------------------------------
// 生成模拟银行卡号 (6222 开头 + 16位随机数)
_generateCardNumber() {
let num = '6222';
for (let i = 0; i < 16; i++) {
num += Math.floor(Math.random() * 10);
}
return num.replace(/(\d{4})(?=\d)/g, '$1 '); // 每4位加空格
}
// 记录日志(带时间戳)
_log(type, message) {
const time = new Date().toLocaleTimeString('zh-CN', { hour12: false });
this.transactions.push({ time, type, message });
}
// 格式化金额
_formatMoney(amount) {
return ¥${amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')};
}
// 校验金额合法性
_validateAmount(amount) {
if (typeof amount !== 'number' || isNaN(amount)) {
return { ok: false, msg: '❌ 金额必须是有效数字' };
}
if (amount <= 0) {
return { ok: false, msg: '❌ 金额必须大于 0' };
}
if (amount > 1000000) {
return { ok: false, msg: '❌ 单笔金额不能超过 1,000,000' };
}
return { ok: true };
}
// ----------------------------------------------------------
// 公共业务方法
// ----------------------------------------------------------
// 1. 查询余额
queryBalance() {
console.log('\n📊 ========== 账户概览 ==========');
console.log(🏦 银行:${this.account.bankName});
console.log(💳 卡号:${this.account.cardNumber});
console.log(👤 户主:${this.account.holder});
console.log(💰 余额:${this._formatMoney(this.account.balance)} ${this.account.currency});
console.log('================================\n');
return this.account.balance;
}
// 2. 存款
deposit(amount) {
const check = this._validateAmount(amount);
if (!check.ok) {
console.log(check.msg);
return false;
}
this.account.balance += amount;
this._log('存款', `存入 ${this._formatMoney(amount)},余额 ${this._formatMoney(this.account.balance)}`);
console.log(`✅ 存款成功!存入 ${this._formatMoney(amount)},当前余额 ${this._formatMoney(this.account.balance)}`);
return true;
}
// 3. 取款
withdraw(amount) {
const check = this._validateAmount(amount);
if (!check.ok) {
console.log(check.msg);
return false;
}
if (amount > this.account.balance) {
console.log(`❌ 取款失败:余额不足(当前余额 ${this._formatMoney(this.account.balance)})`);
this._log('取款失败', `尝试取款 ${this._formatMoney(amount)},余额不足`);
return false;
}
this.account.balance -= amount;
this._log('取款', `取出 ${this._formatMoney(amount)},余额 ${this._formatMoney(this.account.balance)}`);
console.log(`✅ 取款成功!取出 ${this._formatMoney(amount)},当前余额 ${this._formatMoney(this.account.balance)}`);
return true;
}
// 4. 转账
transfer(targetCard, amount) {
// 校验对方卡号(简单校验:必须为字符串且长度大于10)
if (typeof targetCard !== 'string' || targetCard.replace(/\s/g, '').length < 10) {
console.log('❌ 转账失败:对方卡号格式不正确');
return false;
}
const check = this._validateAmount(amount);
if (!check.ok) {
console.log(check.msg);
return false;
}
if (amount > this.account.balance) {
console.log(`❌ 转账失败:余额不足(当前余额 ${this._formatMoney(this.account.balance)})`);
this._log('转账失败', `向 ${targetCard} 转账 ${this._formatMoney(amount)},余额不足`);
return false;
}
this.account.balance -= amount;
this._log('转账', `向 ${targetCard} 转账 ${this._formatMoney(amount)},余额 ${this._formatMoney(this.account.balance)}`);
console.log(`✅ 转账成功!向 ${targetCard} 转账 ${this._formatMoney(amount)},当前余额 ${this._formatMoney(this.account.balance)}`);
return true;
}
// 5. 打印交易流水
printStatement() {
console.log('\n📋 ========== 交易流水 ==========');
if (this.transactions.length === 0) {
console.log('暂无交易记录');
} else {
this.transactions.forEach((tx, index) => {
console.log(${String(index + 1).padStart(2, '0')}. [${tx.time}] ${tx.type} ${tx.message});
});
}
console.log('================================\n');
}
// 6. 重置账户(用于测试)
reset(initialBalance = 10000) {
this.account.balance = initialBalance;
this.transactions = [];
this._log('重置', 账户已重置,余额 ${this._formatMoney(initialBalance)});
console.log(🔄 账户已重置,当前余额 ${this._formatMoney(initialBalance)});
}
}
// ============================================================
// 演示脚本 —— 模拟用户操作流程
// ============================================================
console.log('🏦 欢迎使用 中国工商银行 模拟器 (纯JS版)\n');
// 创建账户,初始余额 10000 元
const bank = new ICBCBankSimulator(10000);
// 1. 查询余额
bank.queryBalance();
// 2. 存款 5200 元
bank.deposit(5200);
// 3. 取款 3000 元
bank.withdraw(3000);
// 4. 向他人转账 2000 元
bank.transfer('6222 8888 6666 1234', 2000);
// 5. 尝试超额取款(触发失败逻辑)
bank.withdraw(999999);
// 6. 尝试非法金额(触发校验)
bank.deposit(-100);
// 7. 再次查询余额
bank.queryBalance();
// 8. 打印完整交易流水
bank.printStatement();
// ============================================================
// 如果想手动调用,可以在控制台执行:
// bank.deposit(1000)
// bank.withdraw(500)
// bank.transfer('6222 1234 5678 9012', 300)
// bank.queryBalance()
// bank.printStatement()
// ============================================================
代码要点解析
模块 说明
类封装 用 ICBCBankSimulator 类封装账户数据与全部业务逻辑,便于复用与扩展
私有方法 下划线开头的方法(_log、_validateAmount 等)约定为内部使用
校验机制 金额校验 + 余额校验,保证业务安全
日志系统 每次操作自动记录时间戳与描述,可随时打印流水
卡号生成 模拟 6222 开头的 16 位工行卡号,自动每 4 位加空格
金额格式化 千分位分隔 + 两位小数,符合银行展示规范
运行方式
方式一:浏览器控制台
打开 Chrome / Edge 开发者工具(F12)
切换到 Console 面板
粘贴全部代码并回车,即可看到完整演示输出
方式二:Node.js
bash
node icbc-simulator.js
方式三:手动交互测试
运行后可在控制台继续调用:
javascript
bank.deposit(8888); // 存款
bank.withdraw(666); // 取款
bank.transfer('6222 1111 2222 3333', 500); // 转账
bank.queryBalance(); // 查余额
bank.printStatement(); // 查流水
全部逻辑仅依赖原生 JS,无任何第三方库,适合用于教学演示或作为银行类业务逻辑的骨架。