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 物件。

返回值

如果 time1time2 之前,則返回 -1;如果它們相同,則返回 0;如果 time1time2 之後,則返回 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

瀏覽器相容性

另見