Intl.Collator

Baseline 已廣泛支援

此功能已成熟,可跨多種裝置和瀏覽器版本使用。自 2017 年 9 月以來,它已在瀏覽器中提供。

Intl.Collator 物件支援區分語言的字串比較。

試一試

console.log(["Z", "a", "z", "ä"].sort(new Intl.Collator("de").compare));
// Expected output: Array ["a", "ä", "z", "Z"]

console.log(["Z", "a", "z", "ä"].sort(new Intl.Collator("sv").compare));
// Expected output: Array ["a", "z", "Z", "ä"]

console.log(
  ["Z", "a", "z", "ä"].sort(
    new Intl.Collator("de", { caseFirst: "upper" }).compare,
  ),
);
// Expected output: Array ["a", "ä", "Z", "z"]

建構函式

Intl.Collator()

建立一個新的 Collator 物件。

靜態方法

Intl.Collator.supportedLocalesOf()

返回一個數組,其中包含提供的區域設定中受支援的那些區域設定,而無需回退到執行時預設區域設定。

例項屬性

這些屬性定義在 Intl.Collator.prototype 上,並被所有 Intl.Collator 例項共享。

Intl.Collator.prototype.constructor

建立了例項物件的建構函式。對於 Intl.Collator 例項,初始值為 Intl.Collator 建構函式。

Intl.Collator.prototype[Symbol.toStringTag]

[Symbol.toStringTag] 屬性的初始值為字串 "Intl.Collator"。此屬性用於 Object.prototype.toString()

例項方法

Intl.Collator.prototype.compare()

Getter 函式,根據此 Intl.Collator 物件的排序順序比較兩個字串。

Intl.Collator.prototype.resolvedOptions()

返回一個新的物件,其中包含在物件初始化期間計算出的區域設定和排序選項。

示例

使用 Collator

以下示例演示了一個字串在另一個字串之前、之後或同等位置的不同潛在結果

js
console.log(new Intl.Collator().compare("a", "c")); // -1, or some other negative value
console.log(new Intl.Collator().compare("c", "a")); // 1, or some other positive value
console.log(new Intl.Collator().compare("a", "a")); // 0

請注意,上面程式碼中顯示的結果可能因瀏覽器和瀏覽器版本而異。這是因為這些值是實現特定的。也就是說,規範只要求“之前”和“之後”的值分別為負數和正數。

使用語言環境

Intl.Collator.prototype.compare() 提供的結果因語言而異。為了獲得應用程式使用者介面所用語言的排序順序,請確保使用 locales 引數指定該語言(以及可能的備用語言)。

js
// in German, ä sorts with a
console.log(new Intl.Collator("de").compare("ä", "z"));
// -1, or some other negative value

// in Swedish, ä sorts after z
console.log(new Intl.Collator("sv").compare("ä", "z"));
// 1, or some other positive value

使用選項

Intl.Collator.prototype.compare() 提供的結果可以使用 options 引數進行自定義。

js
// in German, ä has a as the base letter
console.log(new Intl.Collator("de", { sensitivity: "base" }).compare("ä", "a"));
// 0

// in Swedish, ä and a are separate base letters
console.log(new Intl.Collator("sv", { sensitivity: "base" }).compare("ä", "a"));
// 1, or some other positive value

規範

規範
ECMAScript® 2026 國際化 API 規範
# collator-objects

瀏覽器相容性

另見