← 中文资源

简体中文版本

Intl.DisplayNames 把代码翻译成本地化标签

Intl.DisplayNames 把语言与区域代码翻译成指定 locale 的显示名称:未知代码返回原码不抛错,同一代码在不同 locale 得到不同标签,适合直接渲染。

阅读英文原文

运行结果

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

US: 美国 | JP: 日本
zh-CN: Chinese (China) | de: German
DE in zh: 德国 | DE in en: Germany
zh-Hans: Simplified Chinese
US=美国 | JP=日本 | DE=德国
unknown: XX

实现说明

各个操作都建立在顶层绑定之上: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'));