乘法 (*)
乘法 (*) 運算子用於計算運算元的乘積。
試一試
console.log(3 * 4);
// Expected output: 12
console.log(-3 * 4);
// Expected output: -12
console.log("3" * 2);
// Expected output: 6
console.log("foo" * 2);
// Expected output: NaN
語法
js
x * y
描述
* 運算子針對兩種型別的運算元進行了過載:數字(number)和 BigInt。它首先會將兩個運算元強制轉換為數值,然後檢查它們的型別。如果兩個運算元都變為 BigInt,則執行 BigInt 乘法;否則,執行數字乘法。如果一個運算元變為 BigInt 而另一個變為數字,則會丟擲 TypeError。
示例
使用數字進行乘法運算
js
2 * 2; // 4
-2 * 2; // -4
Infinity * 0; // NaN
Infinity * Infinity; // Infinity
其他非 BigInt 值被強制轉換為數字
js
"foo" * 2; // NaN
"2" * 2; // 4
使用 BigInt 進行乘法運算
js
2n * 2n; // 4n
-2n * 2n; // -4n
你不能在乘法運算中混合使用 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); // 4n
Number(2n) * 2; // 4
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-multiplicative-operators |
瀏覽器相容性
載入中…