試一試
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 |
瀏覽器相容性
載入中…