除法(/)

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

¥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

基本划分

¥Basic division

js
1 / 2; // 0.5

Math.floor(3 / 2); // 1

1.0 / 2.0; // 0.5

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

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

// To do division with a BigInt and a non-BigInt, convert either operand
2n / BigInt(2); // 1n
Number(2n) / 2; // 1

被零除

¥Division by zero

js
2.0 / 0; // Infinity

2.0 / 0.0; // Infinity, because 0.0 === 0

2.0 / -0.0; // -Infinity

2n / 0n; // RangeError: Division by zero

规范

Specification
ECMAScript Language Specification
# sec-multiplicative-operators

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看