语法错误:无效的 BigInt 语法

当字符串值被强制转换为 BigInt 但无法解析为整数时,会发生 JavaScript 异常 "无效的 BigInt 语法"。

¥The JavaScript exception "invalid BigInt syntax" occurs when a string value is being coerced to a BigInt but it failed to be parsed as an integer.

信息

¥Message

SyntaxError: Cannot convert x to a BigInt (V8-based)
SyntaxError: invalid BigInt syntax (Firefox)
SyntaxError: Failed to parse String to BigInt (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

当使用 BigInt() 函数将字符串转换为 BigInt 时,将以与源代码相同的方式解析字符串,并且结果值必须是整数值。

¥When using the BigInt() function to convert a string to a BigInt, the string will be parsed in the same way as source code, and the resulting value must be an integer value.

示例

¥Examples

无效案例

¥Invalid cases

js
const a = BigInt("1.5");
const b = BigInt("1n");
const c = BigInt.asIntN(4, "8n");
// SyntaxError: invalid BigInt syntax

有效案例

¥Valid cases

js
const a = BigInt("1");
const b = BigInt("  1   ");
const c = BigInt.asIntN(4, "8");

也可以看看

¥See also