Intl.ListFormat.prototype.format()

Baseline 已廣泛支援

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

format() 方法是 Intl.ListFormat 例項的一個方法,它返回一個具有特定語言表示的列表的字串。

試一試

const vehicles = ["Motorcycle", "Bus", "Car"];

const formatter = new Intl.ListFormat("en", {
  style: "long",
  type: "conjunction",
});
console.log(formatter.format(vehicles));
// Expected output: "Motorcycle, Bus, and Car"

const formatter2 = new Intl.ListFormat("de", {
  style: "short",
  type: "disjunction",
});
console.log(formatter2.format(vehicles));
// Expected output: "Motorcycle, Bus oder Car"

const formatter3 = new Intl.ListFormat("en", { style: "narrow", type: "unit" });
console.log(formatter3.format(vehicles));
// Expected output: "Motorcycle Bus Car"

語法

js
format(list)

引數

list

一個可迭代物件,例如陣列,包含字串。省略它會導致格式化空陣列,這可能會有點令人困惑,因此建議始終顯式傳遞一個列表。

返回值

一個特定語言格式化的字串,表示列表中的元素。

注意: 大多數情況下,format() 返回的格式是一致的。然而,輸出可能因實現而異,即使在同一區域設定下也是如此 — 輸出差異是故意的,並且規範允許。它也可能不是您期望的。例如,字串可能使用不間斷空格,或者被雙向控制字元包圍。您不應將 format() 的結果與硬編碼的常量進行比較。

示例

使用格式

以下示例展示瞭如何使用英語建立列表格式化程式。

js
const list = ["Motorcycle", "Bus", "Car"];

console.log(
  new Intl.ListFormat("en-GB", { style: "long", type: "conjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus and Car

console.log(
  new Intl.ListFormat("en-GB", { style: "short", type: "disjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus or Car

console.log(
  new Intl.ListFormat("en-GB", { style: "narrow", type: "unit" }).format(list),
);
// Motorcycle Bus Car

規範

規範
ECMAScript® 2026 國際化 API 規範
# sec-Intl.ListFormat.prototype.format

瀏覽器相容性

另見