乘法(*)

乘法 (*) 运算符生成操作数的乘积。

¥The multiplication (*) operator produces the product of the operands.

Try it

语法

¥Syntax

js
x * y

描述

¥Description

* 运算符针对两种类型的操作数进行重载:编号和 BigInt。它首先 将两个操作数强制转换为数值 并测试它们的类型。如果两个操作数都变成 BigInt,则执行 BigInt 乘法;否则,它执行数字乘法。如果一个操作数变为 BigInt 而另一个操作数变为数字,则抛出 TypeError

¥The * operator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt multiplication if both operands become BigInts; otherwise, it performs number multiplication. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

示例

¥Examples

使用数字进行乘法

¥Multiplication using numbers

js
2 * 2; // 4
-2 * 2; // -4

无穷大乘法

¥Multiplication with Infinity

js
Infinity * 0; // NaN
Infinity * Infinity; // Infinity

与非数字的乘法

¥Multiplication with non-numbers

js
"foo" * 2; // NaN
"2" * 2; // 4

使用 BigInt 进行乘法

¥Multiplication using BigInts

js
2n * 2n; // 4n
-2n * 2n; // -4n

2n * 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions

// To multiply a BigInt with a non-BigInt, convert either operand
2n * BigInt(2); // 4n
Number(2n) * 2; // 4

规范

Specification
ECMAScript Language Specification
# sec-multiplicative-operators

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看