Temporal.PlainYearMonth.compare()
Temporal.PlainYearMonth.compare() 靜態方法返回一個數字(-1、0 或 1),指示第一個年月早於、等於還是晚於第二個年月。這等同於比較它們底層的 ISO 8601 日期。來自不同日曆的兩個年月,如果它們在同一個 ISO 日期開始,可能會被視為相等。
注意: PlainYearMonth 物件會跟蹤一個參考 ISO 日期,該日期也用於比較。使用 Temporal.PlainYearMonth.from() 方法時會自動設定此日期,但可以使用 Temporal.PlainYearMonth() 建構函式手動設定,這會導致兩個等效的年月被視為不同,如果它們具有不同的參考日期。因此,您應該避免直接使用建構函式,而是優先使用 from() 方法。
語法
js
Temporal.PlainYearMonth.compare(yearMonth1, yearMonth2)
引數
yearMonth1-
一個字串、物件或
Temporal.PlainYearMonth例項,表示要比較的第一個年月。它使用與Temporal.PlainYearMonth.from()相同的演算法轉換為Temporal.PlainYearMonth物件。 yearMonth2-
要比較的第二個年月,使用與
yearMonth1相同的演算法轉換為Temporal.PlainYearMonth物件。
返回值
如果 yearMonth1 早於 yearMonth2,則返回 -1;如果它們相同,則返回 0;如果 yearMonth1 晚於 yearMonth2,則返回 1。它們透過其底層的日期值(通常是該月份的第一天)進行比較,忽略它們的日曆。
示例
使用 Temporal.PlainYearMonth.compare()
js
const ym1 = Temporal.PlainYearMonth.from("2021-08");
const ym2 = Temporal.PlainYearMonth.from("2021-09");
console.log(Temporal.PlainYearMonth.compare(ym1, ym2)); // -1
const ym3 = Temporal.PlainYearMonth.from("2021-07");
console.log(Temporal.PlainYearMonth.compare(ym1, ym3)); // 1
比較不同日曆中的年月
js
const ym1 = Temporal.PlainYearMonth.from({ year: 2021, month: 8 });
const ym2 = Temporal.PlainYearMonth.from({
year: 2021,
month: 8,
calendar: "islamic-umalqura",
});
const ym3 = Temporal.PlainYearMonth.from({
year: 2021,
month: 8,
calendar: "hebrew",
});
console.log(ym1.toString()); // "2021-08"
console.log(ym2.toString()); // "2582-12-17[u-ca=islamic-umalqura]"
console.log(ym3.toString()); // "-001739-04-06[u-ca=hebrew]"
console.log(Temporal.PlainYearMonth.compare(ym1, ym2)); // -1
console.log(Temporal.PlainYearMonth.compare(ym1, ym3)); // 1
對年月陣列進行排序
此 compare() 函式的目的是作為比較器,傳遞給 Array.prototype.sort() 和相關函式。
js
const months = [
Temporal.PlainYearMonth.from({ year: 2021, month: 8 }),
Temporal.PlainYearMonth.from({
year: 2021,
month: 8,
calendar: "islamic-umalqura",
}),
Temporal.PlainYearMonth.from({ year: 2021, month: 8, calendar: "hebrew" }),
];
months.sort(Temporal.PlainYearMonth.compare);
console.log(months.map((d) => d.toString()));
// [ "-001739-04-06[u-ca=hebrew]", "2021-08", "2582-12-17[u-ca=islamic-umalqura]" ]
規範
| 規範 |
|---|
| Temporal # sec-temporal.plainyearmonth.compare |
瀏覽器相容性
載入中…