除法 (/)
除法 (/) 運算子用於計算其運算元的商,其中左運算元是被除數,右運算元是除數。
試一試
console.log(12 / 2);
// Expected output: 6
console.log(3 / 2);
// Expected output: 1.5
console.log(6 / "3");
// Expected output: 2
console.log(2 / 0);
// Expected output: Infinity
語法
js
x / y
描述
/ 運算子對兩種型別的運算元進行了過載:number 和 BigInt。它首先將兩個運算元強制轉換為數值,然後測試它們的型別。如果兩個運算元都變為 BigInt,則執行 BigInt 除法;否則,執行 number 除法。如果一個運算元變為 BigInt,而另一個變為 number,則會丟擲 TypeError。
對於 BigInt 除法,結果是兩個運算元向零截斷的商,餘數被丟棄。如果除數 y 是 0n,則會丟擲 RangeError。這是因為數字除以零會返回 Infinity 或 -Infinity,但 BigInt 沒有無窮大的概念。
示例
使用數字進行除法
js
1 / 2; // 0.5
Math.floor(3 / 2); // 1
1.0 / 2.0; // 0.5
2 / 0; // Infinity
2.0 / 0.0; // Infinity, because 0.0 === 0
2.0 / -0.0; // -Infinity
其他非 BigInt 值被強制轉換為數字
js
5 / "2"; // 2.5
5 / "foo"; // NaN
使用 BigInt 進行除法
js
1n / 2n; // 0n
5n / 3n; // 1n
-1n / 3n; // 0n
1n / -3n; // 0n
2n / 0n; // RangeError: BigInt division by zero
不能在除法中混合使用 BigInt 和數字運算元。
js
2n / 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions
2 / 2n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
要對 BigInt 和非 BigInt 進行除法,請轉換其中一個運算元
js
2n / BigInt(2); // 1n
Number(2n) / 2; // 1
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-multiplicative-operators |
瀏覽器相容性
載入中…