← 中文资源

简体中文版本

Intl.supportedValuesOf 列出可用值

列出日历、单位、货币与时区,再把受支持的单位传给 NumberFormat 格式化。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

calendars: 18 | sample: buddhist,chinese,coptic,dangi
units: 45 | sample: acre,bit,byte,celsius,centimeter
currencies: 162 | sample: AED,AFN,ALL,AMD,ANG
time zones: 418 | has Europe/London: true
calendar: 18
currency: 162
numberingSystem: 78
timeZone: 418
unit: 45
formatted: 3 meters
EUR supported: true
XYZ supported: false

实现说明

for (const key of ['calendar', 'currency', 'numberingSystem', 'timeZone', 'unit']) 承担全部的逐项处理。 calendars、units、currencies、zones 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 直接运行文件,输出会带上标签,比如 calendars:、units:、currencies:——输出的每一行都能指回产生它的那次调用。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件用顶层绑定保存自己的状态:calendars、units、currencies。

核心语句

const supported = new Set(Intl.supportedValuesOf('currency'));
const formatter = new Intl.NumberFormat('en-US', { style: 'unit', unit, unitDisplay: 'long' });
const currencies = Intl.supportedValuesOf('currency');

代码示例

const calendars = Intl.supportedValuesOf('calendar');
const units = Intl.supportedValuesOf('unit');
const currencies = Intl.supportedValuesOf('currency');
const zones = Intl.supportedValuesOf('timeZone');

console.log('calendars:', calendars.length, '| sample:', calendars.slice(0, 4).join(','));
console.log('units:', units.length, '| sample:', units.slice(0, 5).join(','));
console.log('currencies:', currencies.length, '| sample:', currencies.slice(0, 5).join(','));
console.log('time zones:', zones.length, '| has Europe/London:', zones.includes('Europe/London'));

for (const key of ['calendar', 'currency', 'numberingSystem', 'timeZone', 'unit']) {
  console.log(key + ':', Intl.supportedValuesOf(key).length);
}

const unit = units.includes('meter') ? 'meter' : units[0];
const formatter = new Intl.NumberFormat('en-US', { style: 'unit', unit, unitDisplay: 'long' });
console.log('formatted:', formatter.format(3));

const supported = new Set(Intl.supportedValuesOf('currency'));
console.log('EUR supported:', supported.has('EUR'));
console.log('XYZ supported:', supported.has('XYZ'));