一元正號(+)
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
一元正號(+
)運算子會放在運算元前面,並回傳其運算元,但如果運算元不是數字,則會嘗試將其轉換為數字。
嘗試一下
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
說明
範例
搭配數字使用
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 |