Intl.DisplayNames.prototype.of()

Baseline 已廣泛支援

此特性已得到良好支援,可在多種裝置和瀏覽器版本上使用。自 2021 年 4 月起,所有瀏覽器均已支援此特性。

Intl.DisplayNames 例項的 of() 方法接收一個程式碼,並根據例項化此 Intl.DisplayNames 物件時提供的區域設定和選項返回一個字串。

試一試

const regionNamesInEnglish = new Intl.DisplayNames(["en"], { type: "region" });
const regionNamesInTraditionalChinese = new Intl.DisplayNames(["zh-Hant"], {
  type: "region",
});

console.log(regionNamesInEnglish.of("US"));
// Expected output: "United States"

console.log(regionNamesInTraditionalChinese.of("US"));
// Expected output: "美國"

語法

js
of(code)

引數

code

要提供的 code 取決於 type

返回值

特定於語言的格式化字串,如果輸入沒有資料且 fallback"none",則返回 undefined

注意: 僅當 code 在結構上有效時,才會使用 fallback。請參閱 使用 fallback

異常

RangeError

如果 code 對於給定的 type 在結構上無效,則會丟擲此錯誤。

示例

使用 of 方法

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"

const languageNamesStandard = new Intl.DisplayNames("fr", {
  type: "language",
  languageDisplay: "standard",
});
languageNamesStandard.of("fr-CA"); // "français (Canada)"

const languageNamesDialect = new Intl.DisplayNames("fr", {
  type: "language",
  languageDisplay: "dialect",
});
languageNamesDialect.of("fr-CA"); // "français canadien"

使用 fallback

Intl.DisplayNames 使用 fallback: "code" 構建時,如果輸入看起來在結構上有效但沒有該輸入的資料,of() 方法將返回 code。如果 fallback"none",則返回 undefined

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,而不是使用 fallback。

js
console.log(
  new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZLC"),
); // throws RangeError: invalid value "ZLC" for option region

規範

規範
ECMAScript® 2026 國際化 API 規範
# sec-Intl.DisplayNames.prototype.of

瀏覽器相容性

另見