如何通过货币代码从dinero.js/currencies包中获取对应货币?
通过货币代码获取dinero.js货币的最简实现方法
dinero.js的@dinero.js/currencies包本身就以大写ISO 4217货币代码作为导出键(比如USD、EUR),所以最简单的实现方式就是直接利用模块导出的对象进行属性访问,同时兼容输入的大小写问题。
实现步骤与代码
ES模块写法
import * as allCurrencies from '@dinero.js/currencies'; function getCurrency(currencyCode) { // 统一转为大写,兼容大小写输入 const normalizedCode = currencyCode.toUpperCase(); // 直接通过属性访问获取对应货币,不存在则返回null return allCurrencies[normalizedCode] ?? null; }
CommonJS写法
const allCurrencies = require('@dinero.js/currencies'); function getCurrency(currencyCode) { const normalizedCode = currencyCode.toUpperCase(); return allCurrencies[normalizedCode] ?? null; }
使用示例
// 匹配大写代码 const usd = getCurrency('USD'); // 兼容小写输入 const eur = getCurrency('eur'); // 无效代码返回null const invalidCurrency = getCurrency('XYZ');
说明
- 包内的每个货币实例都以大写货币代码作为导出名称,直接通过对象属性访问是最高效的方式
- 转换为大写是为了避免用户输入大小写不一致导致的匹配失败
- 可以根据需求调整不存在时的返回值,比如改为抛出错误或返回默认货币
内容的提问来源于stack exchange,提问作者Antoine
相关产品推荐
相关产品推荐

