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

语法

¥Syntax

js
of(code)

参数

¥Parameters

code

要提供的 code 取决于 type

返回值

¥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: fallback is only used if code is structurally valid. See using fallback.

例外情况

¥Exceptions

RangeError

如果 code 在结构上对于给定的 type 无效,则抛出该异常。

示例

¥Examples

使用 of 方法

¥Using the of method

js
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.

js
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.

js
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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also