減法 (-)
減法運算子 (-) 將兩個運算元相減,得到它們的差。
試一試
console.log(5 - 3);
// Expected output: 2
console.log(3.5 - 5);
// Expected output: -1.5
console.log(5 - "hello");
// Expected output: NaN
console.log(5 - true);
// Expected output: 4
語法
js
x - y
描述
- 運算子對於兩種型別的運算元是過載的:數字(number)和 BigInt。它首先 將兩個運算元強制轉換為數字值,然後測試它們的型別。如果兩個運算元都變為 BigInt,則執行 BigInt 減法;否則,執行數字減法。如果一個運算元變為 BigInt 而另一個變為數字,則丟擲 TypeError。
示例
使用數字進行減法
js
5 - 3; // 2
3 - 5; // -2
其他非 BigInt 值被強制轉換為數字
js
"foo" - 3; // NaN; "foo" is converted to the number NaN
5 - "3"; // 2; "3" is converted to the number 3
使用 BigInt 進行減法
js
2n - 1n; // 1n
你不能在減法中混合使用 BigInt 和數字運算元。
js
2n - 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions
2 - 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
要使用 BigInt 和非 BigInt 進行減法,請轉換其中一個運算元。
js
2n - BigInt(1); // 1n
Number(2n) - 1; // 1
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-subtraction-operator-minus |
瀏覽器相容性
載入中…