大网数据广告活动
Web 标准与前端开发

Temporal.Duration.prototype.with()

· 52CE 我爱测

The **`with()`** method of Temporal.Duration instances returns a new `Temporal.Duration` object representing this duration with some fields replaced by new values. Because all `Temporal` objects are designed to be immutable, this method essentially functions as the setter for the

The with() method of Temporal.Duration instances returns a new Temporal.Duration object representing this duration with some fields replaced by new values. Because all Temporal objects are designed to be immutable, this method essentially functions as the setter for the duration's fields.

Syntax

with(info)

Parameters

  • info
    • : An object containing at least one of the properties recognized by Temporal/Duration/from: years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds. Unspecified properties use the values from the original duration.

Return value

A new Temporal.Duration object, where the fields specified in info that are not undefined are replaced by the corresponding values, and the rest of the fields are copied from the original duration.

Exceptions

  • RangeError
    • : Thrown in one of the following cases:
      • Any of the recognized properties in the info object is not an integer (including non-finite values).
      • A calendar unit (years, months, weeks) has an absolute value ≥ 2<sup>32</sup>.
      • The non-calendar part of the duration (days and below), when expressed in seconds, has an absolute value ≥ 2<sup>53</sup>.
  • TypeError
    • : Thrown in one of the following cases:
      • The info object is not an object.
      • All of the recognized properties in the info object are undefined.

Examples

Using with()

You can use with() to achieve fine-grained control over the fields of a Temporal.Duration object. For example, you can manually balance a duration only on one unit, which round() does not offer:

function balanceMinutes(duration) {
  const { hours, minutes } = duration;
  const totalMinutes = hours * 60 + minutes;
  const balancedMinutes = totalMinutes % 60;
  const balancedHours = (totalMinutes - balancedMinutes) / 60;
  return duration.with({ hours: balancedHours, minutes: balancedMinutes });
}

const d1 = Temporal.Duration.from({ hours: 100, minutes: 100, seconds: 100 });
const d2 = balanceMinutes(d1);
console.log(d2.hours); // 101
console.log(d2.minutes); // 40
console.log(d2.seconds); // 100; remains unbalanced

Specifications

Browser compatibility

See also

  • Temporal.Duration
  • Temporal/Duration/from
  • Temporal/Duration/add
  • Temporal/Duration/subtract
  • Temporal/Duration/round

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。