除法 (/)

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

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

试一试

console.log(12 / 2);
// Expected output: 6

console.log(3 / 2);
// Expected output: 1.5

console.log(6 / "3");
// Expected output: 2

console.log(2 / 0);
// Expected output: Infinity

语法

js
x / y

描述

/ 运算符对两种类型的操作数进行了重载:number 和 BigInt。它首先将两个操作数强制转换为数值,然后测试它们的类型。如果两个操作数都变为 BigInt,则执行 BigInt 除法;否则,执行 number 除法。如果一个操作数变为 BigInt,而另一个变为 number,则会抛出 TypeError

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

示例

使用数字进行除法

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

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

使用 BigInt 进行除法

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

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

不能在除法中混合使用 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); // 1n
Number(2n) / 2; // 1

规范

规范
ECMAScript® 2026 语言规范
# sec-multiplicative-operators

浏览器兼容性

另见