余数(%)
余数 (%
) 运算符返回一个操作数除以第二个操作数时剩下的余数。它总是带有股息的符号。
¥The remainder (%
) operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
Try it
语法
描述
¥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 remainder if both operands become BigInts; otherwise, it performs number remainder. A TypeError
is thrown if one operand becomes a BigInt but the other becomes a number.
对于运算 n % d
,n
称为被除数,d
称为除数。如果操作数之一为 NaN
、n
为 ±Infinity,或者 d
为 ±0,则该运算返回 NaN
。否则,如果 d
为 ±Infinity 或 n
为 ±0,则返回被除数 n
。
¥For the operation n % d
, n
is called the dividend and d
is called the divisor. The operation returns NaN
if one of the operands is NaN
, n
is ±Infinity, or if d
is ±0. Otherwise, if d
is ±Infinity or if n
is ±0, the dividend n
is returned.
当两个操作数均非零且有限时,余数 r
计算为 r := n - d * q
,其中 q
是整数,使得 r
与被除数 n
具有相同符号,同时尽可能接近 0。
¥When both operands are non-zero and finite, the remainder r
is calculated as r := n - d * q
where q
is the integer such that r
has the same sign as the dividend n
while being as close to 0 as possible.
请注意,虽然在大多数语言中,'%' 是余数运算符,但在某些语言(例如 Python、Perl)中,它是模运算符。模定义为 k := n - d * q
,其中 q
是整数,使得 k
与除数 d
具有相同的符号,同时尽可能接近 0。对于符号相同的两个值,两者是等价的,但是当操作数符号不同时,取模结果始终与除数具有相同的符号,而余数与被除数具有相同的符号,这可以使它们不同 d
的一个单位。要在 JavaScript 中获取模数,请使用 ((n % d) + d) % d
代替 n % d
。在 JavaScript 中,模运算(没有专用运算符)用于标准化按位移位运算符(<<
、>>
等)的第二个操作数,使偏移量始终为正值。
¥Note that while in most languages, '%' is a remainder operator, in some (e.g. Python, Perl) it is a modulo operator. Modulo is defined as k := n - d * q
where q
is the integer such that k
has the same sign as the divisor d
while being as close to 0 as possible. For two values of the same sign, the two are equivalent, but when the operands are of different signs, the modulo result always has the same sign as the divisor, while the remainder has the same sign as the dividend, which can make them differ by one unit of d
. To obtain a modulo in JavaScript, in place of n % d
, use ((n % d) + d) % d
. In JavaScript, the modulo operation (which doesn't have a dedicated operator) is used to normalize the second operand of bitwise shift operators (<<
, >>
, etc.), making the offset always a positive value.
对于 BigInt 除法,如果除数 y
是 0n
,则抛出 RangeError
。这是因为数字除零返回 NaN
,但 BigInt 没有 NaN
的概念。
¥For BigInt division, a RangeError
is thrown if the divisor y
is 0n
. This is because number remainder by zero returns NaN
, but BigInt has no concept of NaN
.
示例
剩余正股息
剩余股利为负
带 NaN 的余数
无穷大的余数
规范
Specification |
---|
ECMAScript Language Specification # sec-multiplicative-operators |
浏览器兼容性
BCD tables only load in the browser