Intl.DisplayNames.prototype.of()
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- 如果
type是 "region",code應該是 兩個字母的 ISO 3166 地區程式碼,或者 三位數的 UN M49 區域程式碼。它需要遵循unicode_region_subtag語法。使用大寫程式碼(例如"US"),因為小寫程式碼(例如"us")可能無法在所有地方可靠地工作。 - 如果
type是 "script",code應該是 四個字母的 ISO 15924 指令碼程式碼。它需要遵循unicode_script_subtag語法。 - 如果
type是 "language",code應該能被unicode_language_id非終結符匹配。 - 如果
type是 "currency",code應該是 三個字母的 ISO 4217 貨幣程式碼。它需要包含正好三個字母字元。 - 如果
type是 "dateTimeField",code應該是以下之一:"era"、"year"、"quarter"、"month"、"weekOfYear"、"weekday"、"day"、"dayPeriod"、"hour"、"minute"、"second"、"timeZoneName"。 - 如果
type是 "calendar",code應該是一個 日曆鍵。它需要遵循 Unicode 區域設定識別符號 的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 |
瀏覽器相容性
載入中…