RangeError: BigInt negative exponent
当 BigInt 的指数是负的 BigInt 值时,会发生 JavaScript 异常 "BigInt negative exponent"。
消息
RangeError: Exponent must be positive (V8-based) RangeError: BigInt negative exponent (Firefox) RangeError: Negative exponent is not allowed (Safari)
错误类型
哪里出错了?
幂运算的指数必须为正。由于负指数会取底数的倒数,结果在几乎所有情况下都会介于 -1 和 1 之间,这会被四舍五入为 0n。为了防止出错,不允许使用负指数。在进行幂运算之前,请检查指数是否为非负数。
示例
将负 BigInt 用作指数
js
const a = 1n;
const b = -1n;
const c = a ** b;
// RangeError: BigInt negative exponent
相反,首先检查指数是否为负数,然后要么发出带有更好消息的错误,要么回退到不同的值,例如 0n 或 undefined。
js
const a = 1n;
const b = -1n;
const quotient = b >= 0n ? a ** b : 0n;