乘法 (*)
乘法 (*) 运算符用于计算操作数的乘积。
试一试
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 |
浏览器兼容性
加载中…