RangeError: x can't be converted to BigInt because it isn't an integer

当对非整数的数字使用 BigInt() 函数时,会发生 JavaScript 异常 "x 无法转换为 BigInt,因为它不是整数"。

消息

RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer (V8-based & Firefox)
RangeError: Not an integer (Safari)

错误类型

RangeError.

哪里出错了?

当使用 BigInt() 函数将数字转换为 BigInt 时,该数字必须是整数(即 Number.isInteger 返回 true)。

示例

无效案例

js
const a = BigInt(1.5);
// RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer
const b = BigInt(NaN);
// RangeError: NaN cannot be converted to a BigInt because it is not an integer

有效情况

js
const a = BigInt(1);

另见