实现说明
迭代发生在 for (const input of inputs) 内部——循环之外的语句只执行一遍。
inputs、tags、locale 定义在模块顶层,中间不经过函数作用域。
使用要点
- 跑完文件,输出里会留下标记——
reason:、deduped:、formatter locale:。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件用顶层绑定保存自己的状态:inputs、tags、locale。
核心语句
const locale = new Intl.DateTimeFormat('zh-hant-tw').resolvedOptions().locale;
const tags = Intl.getCanonicalLocales(['EN-us', 'en-US', 'de-de']);
const [tag] = Intl.getCanonicalLocales(input);
代码示例
const inputs = ['en-us', 'ZH-hant-tw', 'fr', 'not a locale'];
for (const input of inputs) {
try {
const [tag] = Intl.getCanonicalLocales(input);
console.log(input, '->', tag);
} catch (error) {
console.log(input, '-> invalid');
console.log('reason:', error.name);
}
}
const tags = Intl.getCanonicalLocales(['EN-us', 'en-US', 'de-de']);
console.log('deduped:', tags.join(','));
const locale = new Intl.DateTimeFormat('zh-hant-tw').resolvedOptions().locale;
console.log('formatter locale:', locale);