Intl.ListFormat.prototype.formatToParts()
Intl.ListFormat 实例的 formatToParts() 方法返回代表不同组件的 Array 个对象,这些组件可用于以区域设置感知的方式格式化值列表。
¥The formatToParts() method of Intl.ListFormat instances
returns an Array of objects representing the different components that
can be used to format a list of values in a locale-aware fashion.
Try it
语法
参数
返回值
描述
¥Description
Intl.ListFormat.prototype.format() 返回列表的格式化版本的字符串(根据给定的区域设置和样式选项),而 formatToParts() 返回格式化字符串的不同组件的数组。
¥Whereas Intl.ListFormat.prototype.format() returns a string being the formatted version
of the list (according to the given locale and style options),
formatToParts() returns an array of the different components of the
formatted string.
结果数组的每个元素都有两个属性:type 和 value。type 属性可以是 "element"(指列表中的值)或 "literal"(指语言构造)。value 属性以字符串形式给出令牌的内容。
¥Each element of the resulting array has two properties: type and
value. The type property may be either
"element", which refers to a value from the list, or
"literal" which refers to a linguistic construct. The value
property gives the content, as a string, of the token.
用于格式化的区域设置和样式选项在构造 Intl.ListFormat 实例时给出。
¥The locale and style options used for formatting are given when constructing the
Intl.ListFormat instance.
示例
使用 formatToParts
¥Using formatToParts
const fruits = ["Apple", "Orange", "Pineapple"];
const myListFormat = new Intl.ListFormat("en-GB", {
style: "long",
type: "conjunction",
});
console.table(myListFormat.formatToParts(fruits));
// [
// { "type": "element", "value": "Apple" },
// { "type": "literal", "value": ", " },
// { "type": "element", "value": "Orange" },
// { "type": "literal", "value": ", and " },
// { "type": "element", "value": "Pineapple" }
// ]
规范
| Specification |
|---|
| ECMAScript Internationalization API Specification # sec-Intl.ListFormat.prototype.formatToParts |
浏览器兼容性
BCD tables only load in the browser