Intl.DurationFormat.prototype.formatToParts()
formatToParts() 方法 Intl.DurationFormat 实例会返回一个对象数组,这些对象代表 format() 方法会返回的格式化字符串的每个部分。它对于使用区域设置特定的标记构建自定义字符串很有用。
语法
formatToParts(duration)
参数
duration可选-
要格式化的持续时间对象。它应该包含以下一个或多个属性:
years,months,weeks,days,hours,minutes,seconds,milliseconds,microseconds,nanoseconds。每个属性的值都应该是一个整数,并且它们的符号应该是一致的。这可以是一个Temporal.Duration对象;有关这些属性的更多信息,请参阅Temporal.Duration文档。
返回值
一个包含部分格式化持续时间的 Array 对象。每个对象有两个或三个属性:type、value,以及可选的 unit,它们都包含一个字符串。按顺序连接 value 字符串将得到与 format() 相同的字符串。这些部分可以被视为直接通过调用 Intl.NumberFormat.prototype.formatToParts() 并传入数值及其各自的单位而获得的。NumberFormat 生成的所有标记都有一个额外的 unit 属性,该属性是输入 unit 的单数形式;这用于编程用途,并且不会进行本地化。本地化的单位作为 NumberFormat 结果的一部分,作为单独的 unit 标记输出。每个持续时间单位的部分将按照调用 Intl.ListFormat.prototype.formatToParts() 并使用 { type: "unit" } 的方式连接起来,因此会插入额外的文字标记。
示例
formatToParts 方法通过将字符串分解为各个部分,从而支持 DurationFormat 格式化程序生成的字符串的区域设置感知格式化。
const duration = {
hours: 7,
minutes: 8,
seconds: 9,
milliseconds: 123,
microseconds: 456,
nanoseconds: 789,
};
new Intl.DurationFormat("en", { style: "long" }).formatToParts(duration);
// Returned value:
[
{ type: "integer", value: "7", unit: "hour" },
{ type: "literal", value: " ", unit: "hour" },
{ type: "unit", value: "hours", unit: "hour" },
{ type: "literal", value: ", " },
{ type: "integer", value: "8", unit: "minute" },
{ type: "literal", value: " ", unit: "minute" },
{ type: "unit", value: "minutes", unit: "minute" },
{ type: "literal", value: ", " },
{ type: "integer", value: "9", unit: "second" },
{ type: "literal", value: " ", unit: "second" },
{ type: "unit", value: "seconds", unit: "second" },
{ type: "literal", value: ", " },
{ type: "integer", value: "123", unit: "millisecond" },
{ type: "literal", value: " ", unit: "millisecond" },
{ type: "unit", value: "milliseconds", unit: "millisecond" },
{ type: "literal", value: ", " },
{ type: "integer", value: "456", unit: "microsecond" },
{ type: "literal", value: " ", unit: "microsecond" },
{ type: "unit", value: "microseconds", unit: "microsecond" },
{ type: "literal", value: ", " },
{ type: "integer", value: "789", unit: "nanosecond" },
{ type: "literal", value: " ", unit: "nanosecond" },
{ type: "unit", value: "nanoseconds", unit: "nanosecond" },
];
规范
| 规范 |
|---|
| Intl.DurationFormat # sec-Intl.DurationFormat.prototype.formatToParts |
浏览器兼容性
加载中…