Temporal.PlainTime.compare()
靜態方法 Temporal.PlainTime.compare() 返回一個數字(-1、0 或 1),表示第一個時間在第二個時間之前、與第二個時間相同或在第二個時間之後。它等同於逐個比較小時、分鐘、秒、毫秒、微秒和納秒欄位。
語法
js
Temporal.PlainTime.compare(time1, time2)
引數
time1-
一個字串、一個物件或一個
Temporal.PlainTime例項,代表要比較的第一個時間。它使用與Temporal.PlainTime.from()相同的演算法轉換為Temporal.PlainTime物件。 time2-
要比較的第二個時間,使用與
time1相同的演算法轉換為Temporal.PlainTime物件。
返回值
如果 time1 在 time2 之前,則返回 -1;如果它們相同,則返回 0;如果 time1 在 time2 之後,則返回 1。
示例
使用 Temporal.PlainTime.compare()
js
const time1 = Temporal.PlainTime.from("12:34:56");
const time2 = Temporal.PlainTime.from("12:34:57");
console.log(Temporal.PlainTime.compare(time1, time2)); // -1
const time3 = Temporal.PlainTime.from("11:34:56");
console.log(Temporal.PlainTime.compare(time1, time3)); // 1
對時間陣列進行排序
此 compare() 函式的目的是作為比較器,傳遞給 Array.prototype.sort() 和相關函式。
js
const times = ["12:34:56", "11:34:56", "12:34:57"];
times.sort(Temporal.PlainTime.compare);
console.log(times);
// [ "11:34:56", "12:34:56", "12:34:57" ]
規範
| 規範 |
|---|
| Temporal # sec-temporal.plaintime.compare |
瀏覽器相容性
載入中…