Temporal.Instant.compare()
静态方法 Temporal.Instant.compare() 返回一个数字(-1、0 或 1),指示第一个瞬间是否早于、等于或晚于第二个瞬间。它等同于比较两个瞬间的 epochNanoseconds。
语法
js
Temporal.Instant.compare(instant1, instant2)
参数
instant1-
一个字符串或一个
Temporal.Instant实例,表示要比较的第一个瞬间。它使用与Temporal.Instant.from()相同的算法转换为Temporal.Instant对象。 instant2-
要比较的第二个瞬间,使用与
instant1相同的算法转换为Temporal.Instant对象。
返回值
如果 instant1 早于 instant2,则返回 -1;如果它们相等,则返回 0;如果 instant1 晚于 instant2,则返回 1。
示例
使用 Temporal.Instant.compare()
js
const instant1 = Temporal.Instant.from("2021-08-01T12:34:56Z");
const instant2 = Temporal.Instant.from("2021-08-01T12:34:56Z");
console.log(Temporal.Instant.compare(instant1, instant2)); // 0
const instant3 = Temporal.Instant.from("2021-08-01T13:34:56Z");
console.log(Temporal.Instant.compare(instant1, instant3)); // -1
对瞬间数组进行排序
此 compare() 函数的目的是作为比较器,传递给 Array.prototype.sort() 和相关函数。
js
const instants = [
Temporal.Instant.from("2021-08-01T12:34:56Z"),
Temporal.Instant.from("2021-08-01T12:34:56+01:00"),
Temporal.Instant.from("2021-08-01T12:34:56-01:00"),
];
instants.sort(Temporal.Instant.compare);
console.log(instants.map((instant) => instant.toString()));
// [ '2021-08-01T11:34:56Z', '2021-08-01T12:34:56Z', '2021-08-01T13:34:56Z' ]
规范
| 规范 |
|---|
| Temporal # sec-temporal.instant.compare |
浏览器兼容性
加载中…