实现说明
各个操作都建立在顶层绑定之上:regionNames、langNames、enRegions、codes。
使用要点
- 每一步打印都带着自己的标签:
US:、zh-CN:、DE in zh:。
常见问题
除了语言运行时还需要什么准备?
什么都不需要——语言运行时是唯一要求。 文件的状态由几个模块级绑定持有:regionNames、langNames、enRegions。
核心语句
const regionNames = new Intl.DisplayNames(['zh-CN'], { type: 'region' });
const langNames = new Intl.DisplayNames(['en'], { type: 'language' });
const enRegions = new Intl.DisplayNames(['en'], { type: 'region' });
代码示例
// Intl.DisplayNames turns language/region codes into display names for the current locale -
// language switchers and region lists render directly, no bundled translation table needed
const regionNames = new Intl.DisplayNames(['zh-CN'], { type: 'region' });
console.log('US:', regionNames.of('US'), '| JP:', regionNames.of('JP'));
const langNames = new Intl.DisplayNames(['en'], { type: 'language' });
console.log('zh-CN:', langNames.of('zh-CN'), '| de:', langNames.of('de'));
// The same code gets different labels under different locales
const enRegions = new Intl.DisplayNames(['en'], { type: 'region' });
console.log('DE in zh:', regionNames.of('DE'), '| DE in en:', enRegions.of('DE'));
// Subtags resolve too: zh-Hans becomes the variant name instead of throwing
console.log('zh-Hans:', langNames.of('zh-Hans'));
// Rendering a picker: map each code in the list to a label for the current locale
const codes = ['US', 'JP', 'DE'];
console.log(codes.map((c) => c + '=' + regionNames.of(c)).join(' | '));
// Invalid or unknown codes come back as the code itself rather than throwing
console.log('unknown:', regionNames.of('XX'));