范围错误:BigInt 负指数

BigInt 为负 BigInt 值的幂时,会发生 JavaScript 异常 "BigInt 负指数"。

¥The JavaScript exception "BigInt negative exponent" occurs when a BigInt is raised to the power of a negative BigInt value.

信息

¥Message

RangeError: Exponent must be positive (V8-based)
RangeError: BigInt negative exponent (Firefox)
RangeError: Negative exponent is not allowed (Safari)

错误类型

¥Error type

RangeError

什么地方出了错?

¥What went wrong?

exponentiation 运算的指数必须为正。由于负指数取底数的倒数,因此几乎在所有情况下结果都在 -1 和 1 之间,四舍五入为 0n。为了发现错误,不允许使用负指数。在求幂之前检查指数是否非负。

¥The exponent of an exponentiation operation must be positive. Since negative exponents would take the reciprocal of the base, the result will be between -1 and 1 in almost all cases, which gets rounded to 0n. To catch mistakes, negative exponents are not allowed. Check if the exponent is non-negative before doing exponentiation.

示例

¥Examples

使用负 BigInt 作为指数

¥Using a negative BigInt as exponent

js
const a = 1n;
const b = -1n;
const c = a ** b;
// RangeError: BigInt negative exponent

相反,首先检查指数是否为负数,然后发出带有更好消息的错误,或者回退到不同的值,例如 0nundefined

¥Instead, check if the exponent is negative first, and either issue an error with a better message, or fallback to a different value, like 0n or undefined.

js
const a = 1n;
const b = -1n;
const quotient = b >= 0n ? a ** b : 0n;

也可以看看

¥See also