You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过货币代码从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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 02:57:52