JS 根据币种判断账号:从 `switch` 到配置映射
2026.11.28 13:57:06 5 0
在支付、订单和财务系统中,经常需要根据币种选择对应的收款账号。例如,人民币订单使用人民币账号,美元订单使用美元账号。本文介绍如何使用 JavaScript 实现币种与账号的匹配,并说明常见的边界处理方式。
## 一、使用 `switch` 判断币种
币种种类较少时,可以使用 `switch`:
```js
function getAccountByCurrency(currency) {
switch (currency) {
case "CNY":
return "account_cny";
case "USD":
return "account_usd";
case "EUR":
return "account_eur";
default:
return null;
}
}
console.log(getAccountByCurrency("USD")); // account_usd
```
这种写法直观,但币种增加后,`switch` 会越来越长,不便于维护。
## 二、使用对象映射
更常见的做法是将币种和账号配置放在对象中:
```js
const accountMap = {
CNY: "account_cny",
USD: "account_usd",
EUR: "account_eur",
};
function getAccountByCurrency(currency) {
const code = String(currency ?? "").trim().toUpperCase();
return accountMap[code] ?? null;
}
console.log(getAccountByCurrency("usd")); // account_usd
console.log(getAccountByCurrency(" USD ")); // account_usd
console.log(getAccountByCurrency("JPY")); // null
```
这里对输入做了标准化处理:
- `String()`:将输入转换为字符串;
- `trim()`:去除首尾空格;
- `toUpperCase()`:统一币种代码大小写;
- `?? null`:币种没有配置时返回 `null`。
## 三、需要区分账号信息时
如果每种币种还需要关联账号名称、账号 ID 或其他配置,可以将映射值设为对象:
```js
const accountMap = {
CNY: {
accountId: "acct_cny_001",
name: "人民币收款账户",
},
USD: {
accountId: "acct_usd_001",
name: "美元收款账户",
},
};
function getAccountByCurrency(currency) {
const code = String(currency ?? "").trim().toUpperCase();
return accountMap[code] ?? null;
}
const account = getAccountByCurrency("CNY");
if (account) {
console.log(account.accountId);
console.log(account.name);
} else {
console.log("暂不支持该币种");
}
```
## 四、处理不支持的币种
如果币种不在配置中,直接返回 `null` 可能不够明确。也可以抛出异常:
```js
function getAccountByCurrency(currency) {
const code = String(currency ?? "").trim().toUpperCase();
const account = accountMap[code];
if (!account) {
throw new Error(`暂不支持币种:`);
}
return account;
}
```
调用时可以使用 `try...catch`:
```js
try {
const account = getAccountByCurrency("JPY");
console.log(account);
} catch (error) {
console.error(error.message);
}
```
## 五、注意事项
1. **优先使用 ISO 币种代码**
建议使用 `CNY`、`USD`、`EUR` 等标准代码,而不是 `¥`、`$` 这样的货币符号。同一个符号可能对应多种币种。
2. **明确默认行为**
不支持的币种应返回 `null`、显示错误,或使用明确配置的默认账号。不要在没有业务规则的情况下静默选择某个账号。
3. **不要在前端存放敏感信息**
如果账号配置涉及密钥、支付凭证或敏感账户信息,应由服务端保存并根据币种返回必要的数据。前端映射更适合用于展示或非敏感场景。
## 总结
简单场景可以用 `switch`,币种数量较多或配置需要扩展时,推荐使用对象映射。处理币种时应统一大小写和空格,并为未支持的币种设计清晰的错误处理逻辑。
本文转载自互联网,如有侵权,联系删除
