实现说明
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'));