除法(/)

除法 (/) 运算符生成其操作数的商,其中左操作数是被除数,右操作数是除数。

¥The division (/) operator produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

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 division if both operands become BigInts; otherwise, it performs number division. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

对于 BigInt 除法,结果是将两个操作数的商截断为零,余数被丢弃。如果除数 y0n,则抛出 RangeError。这是因为数字除以零会返回 Infinity-Infinity,但 BigInt 没有无穷大的概念。

¥For BigInt division, the result is the quotient of the two operands truncated towards zero, and the remainder is discarded. A RangeError is thrown if the divisor y is 0n. This is because number division by zero returns Infinity or -Infinity, but BigInt has no concept of infinity.

示例

¥Examples

使用数字进行除法

¥Division using numbers

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 值被强制转换为数字:

¥Other non-BigInt values are coerced to numbers:

js
5 / "2"; // 2.5
5 / "foo"; // NaN

使用 BigInts 进行除法

¥Division using BigInts

js
1n / 2n; // 0n
5n / 3n; // 1n
-1n / 3n; // 0n
1n / -3n; // 0n

2n / 0n; // RangeError: BigInt division by zero

你不能在除法中混合 BigInt 和数字操作数。

¥You cannot mix BigInt and number operands in division.

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 进行除法,请转换任一操作数:

¥To do division with a BigInt and a non-BigInt, convert either operand:

js
2n / BigInt(2); // 1n
Number(2n) / 2; // 1

规范

Specification
ECMAScript Language Specification
# sec-multiplicative-operators

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看