Temporal.PlainDateTime.prototype.valueOf()
valueOf() 方法 Temporal.PlainDateTime 例項會丟擲 TypeError,這會阻止 Temporal.PlainDateTime 例項在算術或比較操作中使用時被 隱式轉換為原始型別。
語法
js
valueOf()
引數
無。
返回值
無。
異常
TypeError-
總是丟擲。
描述
由於 原始型別轉換 和 數字轉換 都在 toString() 之前呼叫 valueOf(),如果 valueOf() 不存在,那麼像 dateTime1 > dateTime2 這樣的表示式會隱式地將它們作為字串進行比較,這可能會產生意外的結果。透過丟擲 TypeError,Temporal.PlainDateTime 例項可以阻止此類隱式轉換。您需要使用 Temporal.PlainDateTime.prototype.toString() 方法顯式地將它們轉換為字串,或者使用 Temporal.PlainDateTime.compare() 靜態方法來比較它們。
示例
Temporal.PlainDateTime 上的算術和比較操作
對 Temporal.PlainDateTime 例項的所有算術和比較操作都應使用專用方法或顯式將其轉換為原始型別。
js
const dt1 = Temporal.PlainDateTime.from("2022-01-01T00:00:00");
const dt2 = Temporal.PlainDateTime.from("2022-07-01T00:00:00");
dt1 > dt2; // TypeError: can't convert PlainDateTime to primitive type
Temporal.PlainDateTime.compare(dt1, dt2); // -1
dt2 - dt1; // TypeError: can't convert PlainDateTime to primitive type
dt2.since(dt1).toString(); // "P181D"
規範
| 規範 |
|---|
| Temporal # sec-temporal.plaindatetime.prototype.valueof |
瀏覽器相容性
載入中…