RangeError: radix must be an integer

Number.prototype.toString()BigInt.prototype.toString() 方法的可選 radix 引數被指定且不在 2 到 36 之間時,JavaScript 會丟擲異常“radix 必須是至少為 2 且不大於 36 的整數”。

訊息

RangeError: toString() radix argument must be between 2 and 36 (V8-based & Safari)
RangeError: radix must be an integer at least 2 and no greater than 36 (Firefox)

錯誤型別

RangeError

哪裡出錯了?

Number.prototype.toString()BigInt.prototype.toString() 方法的可選 radix 引數已被指定。它的值必須是 2 到 36 之間的整數(一個數字),指定用於表示數值的數字系統的基數。例如,十進位制(基數 10)數字 169 在十六進位制(基數 16)中表示為 A9。

為什麼此引數的值限制為 36?大於 10 的基數使用字母字元作為數字;因此,基數不能大於 36,因為拉丁字母(英語和許多其他語言使用)只有 26 個字元。

最常見的基數

示例

無效案例

js
(42).toString(0);
(42).toString(1);
(42).toString(37);
(42).toString(150);
// You cannot use a string like this for formatting:
(12071989).toString("MM-dd-yyyy");

有效情況

js
(42).toString(2); // "101010" (binary)
(13).toString(8); // "15" (octal)
(0x42).toString(10); // "66" (decimal)
(100000).toString(16); // "186a0" (hexadecimal)

另見