Intl.ListFormat

Baseline 已广泛支持

此特性已得到良好支持,可在多种设备和浏览器版本上使用。自 2021 年 4 月起,所有浏览器均已支持此特性。

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"

构造函数

Intl.ListFormat()

创建一个新的 Intl.ListFormat 对象。

静态方法

Intl.ListFormat.supportedLocalesOf()

返回一个数组,其中包含提供的区域设置中受支持的那些区域设置,而无需回退到运行时默认区域设置。

实例属性

这些属性定义在 Intl.ListFormat.prototype 上,并由所有 Intl.ListFormat 实例共享。

Intl.ListFormat.prototype.constructor

创建实例对象的构造函数。对于 Intl.ListFormat 实例,初始值为 Intl.ListFormat 构造函数。

Intl.ListFormat.prototype[Symbol.toStringTag]

[Symbol.toStringTag] 属性的初始值为字符串 "Intl.ListFormat"。此属性用于 Object.prototype.toString()

实例方法

Intl.ListFormat.prototype.format()

返回一个符合语言习惯的格式化字符串,表示列表中的元素。

Intl.ListFormat.prototype.formatToParts()

返回一个对象数组,这些对象表示可以用来以符合区域设置的方式格式化值列表的各个组件。

Intl.ListFormat.prototype.resolvedOptions()

返回一个新对象,其中包含在当前 Intl.ListFormat 对象构造期间计算出的区域设置和样式格式化选项的属性。

示例

使用格式

以下示例展示了如何使用英语创建列表格式化程序。

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

使用 formatToParts

以下示例显示了如何创建返回格式化部分的 List formatter

js
const list = ["Motorcycle", "Bus", "Car"];
console.log(
  new Intl.ListFormat("en-GB", {
    style: "long",
    type: "conjunction",
  }).formatToParts(list),
);

// [ { "type": "element", "value": "Motorcycle" },
//   { "type": "literal", "value": ", " },
//   { "type": "element", "value": "Bus" },
//   { "type": "literal", "value": ", and " },
//   { "type": "element", "value": "Car" } ];

规范

规范
ECMAScript® 2026 国际化 API 规范
# listformat-objects

浏览器兼容性

另见