Temporal.PlainDate.prototype.with()

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

with() 方法用於 Temporal.PlainDate 例項,它會返回一個新的 Temporal.PlainDate 物件,該物件表示此日期,並用新值替換了其中的某些欄位。由於所有 Temporal 物件都設計為不可變的,因此此方法實際上充當了日期欄位的設定器。

要替換 calendarId 屬性,請改用 withCalendar() 方法。

語法

js
with(info)
with(info, options)

引數

info

一個包含 Temporal.PlainDate.from() 識別的至少一個屬性(除了 calendar)的物件:dayeraeraYearmonthmonthCodeyear。未指定的屬性將使用原始日期中的值。您只需要提供 monthmonthCode 中的一個,以及 eraeraYearyear 中的一個,其他欄位將相應更新。

options 可選

包含以下屬性的物件

overflow 可選

一個字串,指定日期元件超出範圍時的行為。可能的值是

"constrain"(預設)

日期元件被限制在有效範圍內。

"reject"

如果日期元件超出範圍,則丟擲 RangeError

返回值

一個新的 Temporal.PlainDate 物件,其中 info 中指定的、非 undefined 的欄位將被相應的值替換,其餘欄位將從原始日期複製。

異常

TypeError

在以下情況之一中丟擲

  • info 不是一個物件。
  • options 不是物件或 undefined
RangeError

在以下情況之一中丟擲

  • 指定相同元件的提供的屬性不一致。
  • 提供的非數字屬性無效;例如,如果 monthCode 在此日曆中從未是有效的月份程式碼。
  • 提供的數字屬性超出範圍,並且 options.overflow 設定為 "reject"
  • 結果不在可表示範圍內,該範圍是距 Unix 紀元 ±(108 + 1) 天,約 ±273,972.6 年。

示例

使用 with()

js
const date = Temporal.PlainDate.from("2021-07-06");
const newDate = date.with({ day: date.daysInMonth });
console.log(newDate.toString()); // 2021-07-31
const nextDecade = date.with({ year: date.year + 10 });
console.log(nextDecade.toString()); // 2031-07-06

有關更多示例,請參閱可以使用 with() 設定的各個屬性的文件。

規範

規範
Temporal
# sec-temporal.plaindate.prototype.with

瀏覽器相容性

另見