Intl.DisplayNames.prototype.of()
Intl.DisplayNames 实例的 of() 方法接收一个代码并根据实例化此 Intl.DisplayNames 对象时提供的区域设置和选项返回一个字符串。
¥The of() method of Intl.DisplayNames instances receives a code and returns a string based on the locale and options provided when instantiating this Intl.DisplayNames object.
Try it
语法
参数
¥Parameters
code-
要提供的
code取决于type:- 如果类型是 "region",则
code应该是 两个字母的 ISO 3166 区域代码 或 三位数的 UN M49 地理区域。要求遵循unicode_region_subtag语法。 - 如果类型是 "script",则
code应该是 四字母 ISO 15924 脚本代码。要求遵循unicode_script_subtag语法。 - 如果类型是 "language",
code应该是unicode_language_id语法的语言代码 ["" 脚本代码]["" 区域代码]("" 变体)子序列。languageCode 是两个字母的 ISO 639-1 语言代码或三个字母的 ISO 639-2 语言代码。 - 如果类型是 "currency",则
code应该是 三字母 ISO 4217 货币代码。要求恰好包含三个字母字符。 - 如果类型为 "dateTimeField",则
code应为以下之一:"era","year","quarter","month","weekOfYear","weekday","day","dayPeriod","hour","minute","second","timeZoneName". - 如果类型是 "calendar",则
code应该是 日历键。需要遵循 Unicode 语言环境标识符 的type语法。
- 如果类型是 "region",则
返回值
¥Return value
特定于语言的格式化字符串,如果没有输入数据,则为 undefined,并且 fallback 为 "none"。
¥A language-specific formatted string, or undefined if there's no data for the input and fallback is "none".
注意:仅当
code结构有效时才使用fallback。参见 使用后备。¥Note:
fallbackis only used ifcodeis structurally valid. See using fallback.
例外情况
示例
使用 of 方法
¥Using the of method
const regionNames = new Intl.DisplayNames("en", { type: "region" });
regionNames.of("419"); // "Latin America"
const languageNames = new Intl.DisplayNames("en", { type: "language" });
languageNames.of("fr"); // "French"
const currencyNames = new Intl.DisplayNames("en", { type: "currency" });
currencyNames.of("EUR"); // "Euro"
使用后备
¥Using fallback
当 Intl.DisplayNames 使用 fallback: "code" 构造时,如果输入看起来结构有效但没有输入数据,则 of() 方法将返回 code。如果 fallback 是 "none",则返回 undefined。
¥When the Intl.DisplayNames is constructed with fallback: "code", the of() method will return the code if the input looks structurally valid but there's no data for the input. If fallback is "none", undefined is returned.
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZL"),
); // "ZL"
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "none" }).of("ZL"),
); // undefined
然而,这只适用于 code 结构有效的情况。例如,如果 type 是 "region",但 code 不遵循 unicode_region_subtag 语法(2 个字母字符或 3 个数字字符),则直接抛出 RangeError,而不使用后备。
¥However, this only applies if the code is structurally valid. For example, if type is "region" but code does not follow the unicode_region_subtag grammar (2 alphabetic characters or 3 numeric characters), a RangeError is directly thrown instead of using the fallback.
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZLC"),
); // throws RangeError: invalid value "ZLC" for option region
规范
| Specification |
|---|
| ECMAScript Internationalization API Specification # sec-Intl.DisplayNames.prototype.of |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also