试一试
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 |
浏览器兼容性
加载中…