Intl.ListFormat.prototype.format()

Intl.ListFormat 实例的 format() 方法返回一个字符串,其中包含列表的特定于语言的表示形式。

¥The format() method of Intl.ListFormat instances returns a string with a language-specific representation of the list.

Try it

语法

¥Syntax

js
format()
format(list)

参数

¥Parameters

list

可迭代对象,例如数组。

返回值

¥Return value

表示列表元素的特定于语言的格式化字符串。

¥A language-specific formatted string representing the elements of the list.

注意:大多数时候,format() 返回的格式是一致的。但是,即使在同一语言环境中,输出也可能因实现而异 - 输出变化是设计使然,并且规范允许。它也可能不是你所期望的。例如,字符串可以使用不间断空格或被双向控制字符包围。你不应该将 format() 的结果与硬编码常量进行比较。

¥Note: Most of the time, the formatting returned by format() is consistent. However, the output may vary between implementations, even within the same locale — output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should not compare the results of format() to hardcoded constants.

描述

¥Description

format() 方法返回一个已根据 Intl.ListFormat 对象中提供的参数进行格式化的字符串。localesoptions 参数自定义 format() 的行为,并让应用指定用于格式化列表的语言约定。

¥The format() method returns a string that has been formatted based on parameters provided in the Intl.ListFormat object. The locales and options parameters customize the behavior of format() and let applications specify the language conventions that should be used to format the list.

示例

¥Examples

使用格式

¥Using format

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

¥The following example shows how to create a List formatter using the English language.

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

规范

Specification
ECMAScript Internationalization API Specification
# sec-Intl.ListFormat.prototype.format

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also