Temporal.PlainYearMonth.prototype.with()

可用性有限

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

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

with() 方法用於 Temporal.PlainYearMonth 例項,它返回一個新的 Temporal.PlainYearMonth 物件,該物件表示此年月,並將部分欄位替換為新值。由於所有 Temporal 物件都設計為不可變的,因此此方法實際上充當了年月欄位的設定器。

沒有明顯的方法可以建立一個表示不同日曆中相同年月的新 Temporal.PlainYearMonth 物件,因此要替換其 calendarId 屬性,你需要先使用 toPlainDate() 將其轉換為 Temporal.PlainDate 物件,更改日曆,然後再轉換回來。

語法

js
with(info)
with(info, options)

引數

info

一個包含 Temporal.PlainYearMonth.from() 認可的至少一個屬性(除 calendar 外)的物件:eraeraYearmonthmonthCodeyear。未指定的屬性將使用原始年月的數值。你只需要提供 monthmonthCode 中的一個,以及 eraeraYearyear 中的一個,另一個將相應地更新。

options 可選

包含以下屬性的物件

overflow 可選

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

"constrain"(預設)

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

"reject"

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

返回值

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

異常

TypeError

在以下情況之一中丟擲

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

在以下情況之一中丟擲

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

示例

使用 with()

js
const ym = Temporal.PlainYearMonth.from("2021-07");
const newYM = ym.with({ year: 2024 });
console.log(newYM.toString()); // "2024-07"

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

規範

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

瀏覽器相容性

另見