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)

錯誤型別

RangeError.

哪裡出錯了?

冪運算的指數必須為正。由於負指數會取底數的倒數,結果在幾乎所有情況下都會介於 -1 和 1 之間,這會被四捨五入為 0n。為了防止出錯,不允許使用負指數。在進行冪運算之前,請檢查指數是否為非負數。

示例

將負 BigInt 用作指數

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

相反,首先檢查指數是否為負數,然後要麼發出帶有更好訊息的錯誤,要麼回退到不同的值,例如 0nundefined

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

另見