Temporal.Duration.prototype.with()
with() 方法是 Temporal.Duration 例項上的一個方法,它會返回一個新的 Temporal.Duration 物件,該物件代表當前時長,並用新值替換其中的某些欄位。由於所有 Temporal 物件都設計為不可變的,因此此方法實際上充當了時長欄位的設定器。
語法
js
with(info)
引數
info-
一個包含
Temporal.Duration.from()所識別的屬性中至少一個的物件:years、months、weeks、days、hours、minutes、seconds、milliseconds、microseconds、nanoseconds。未指定的屬性將沿用原始時長的值。
返回值
一個新的 Temporal.Duration 物件,其中 info 物件中指定的、非 undefined 的欄位將被相應值替換,其餘欄位將從原始時長複製。
異常
RangeError-
在以下情況之一中丟擲
info物件中任何可識別的屬性不是整數(包括非有限值)。- 日曆單位(年、月、周)的絕對值 ≥ 232。
- 持續時間的非日曆部分(天及以下),以秒為單位表示時,其絕對值 ≥ 253。
TypeError-
在以下情況之一中丟擲
info物件不是一個物件。info物件中所有可識別的屬性都為undefined。
示例
使用 with()
您可以使用 with() 來對 Temporal.Duration 物件的欄位進行精細控制。例如,您可以手動 平衡 時長,只在一個單位上進行,這是 round() 方法無法提供的。
js
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
規範
| 規範 |
|---|
| Temporal # sec-temporal.duration.prototype.with |
瀏覽器相容性
載入中…