一元正號(+)
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
一元正號(+)運算子會放在運算元前面,並回傳其運算元,但如果運算元不是數字,則會嘗試將其轉換為數字。
嘗試一下
const x = 1; const y = -1; console.log(+x); // 預期輸出:1 console.log(+y); // 預期輸出:-1 console.log(+""); // 預期輸出:0 console.log(+true); // 預期輸出:1 console.log(+false); // 預期輸出:0 console.log(+"hello"); // 預期輸出:NaN 語法
js
+x 說明
雖然一元負號(-)也可以轉換非數字型別,但一元正號是將某個值轉換為數字最快且最推薦的方式,因為它不會對數字執行其他操作。
一元正號執行的步驟與大多數內建方法預期數字時所使用的數字轉換完全相同。它可以轉換整數和浮點數的字串表示,以及非字串值 true、false 和 null。支援十進位和十六進位(以 0x 為前綴)的整數格式。也支援負數(但十六進位不支援負數)。如果無法解析特定值,則會回傳 NaN。與其他可同時處理數字與 BigInt 的算術運算子不同,對 BigInt 值使用 + 運算子會拋出 TypeError。
範例
>搭配數字使用
js
const x = 1; const y = -1; console.log(+x); // 1 console.log(+y); // -1 搭配非數字使用
js
+true // 1 +false // 0 +null // 0 +[] // 0 +function (val) { return val; } // NaN +1n // throws TypeError: Cannot convert BigInt value to number 規範
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-unary-plus-operator> |