类型错误:无法将 x 转换为 BigInt
当尝试将 Symbol
、null
或 undefined
值转换为 BigInt
,或者需要 BigInt 参数的操作接收数字时,会发生 JavaScript 异常 "x 无法转换为 BigInt"。
¥The JavaScript exception "x can't be converted to BigInt" occurs when attempting to convert a Symbol
, null
, or undefined
value to a BigInt
, or if an operation expecting a BigInt parameter receives a number.
信息
错误类型
什么地方出了错?
¥What went wrong?
当使用 BigInt()
函数将值转换为 BigInt 时,该值将首先转换为基元。然后,如果它不是 BigInt、字符串、数字和布尔值之一,则会抛出错误。
¥When using the BigInt()
function to convert a value to a BigInt, the value would first be converted to a primitive. Then, if it's not one of BigInt, string, number, and boolean, the error is thrown.
某些操作(例如 BigInt.asIntN
)要求参数为 BigInt。在这种情况下传递数字也会引发此错误。
¥Some operations, like BigInt.asIntN
, require the parameter to be a BigInt. Passing in a number in this case will also throw this error.
示例
对无效值使用 BigInt()
¥Using BigInt() on invalid values
const a = BigInt(null);
// TypeError: can't convert null to BigInt
const b = BigInt(undefined);
// TypeError: can't convert undefined to BigInt
const c = BigInt(Symbol("1"));
// TypeError: can't convert Symbol("1") to BigInt
const a = BigInt(1);
const b = BigInt(true);
const c = BigInt("1");
const d = BigInt(Symbol("1").description);
注意:在将值传递给
BigInt()
之前,简单地使用String()
或Number()
将值强制转换为字符串或数字通常不足以避免所有错误。如果字符串不是有效的整数字符串,则抛出 SyntaxError;如果数字不是整数(最明显的是NaN
),则会抛出 RangeError。如果输入范围未知,请在使用BigInt()
之前正确验证。¥Note: Simply coercing the value to a string or number using
String()
orNumber()
before passing it toBigInt()
is usually not sufficient to avoid all errors. If the string is not a valid integer number string, a SyntaxError is thrown; if the number is not an integer (most notably,NaN
), a RangeError is thrown. If the range of input is unknown, properly validate it before usingBigInt()
.
将数字传递给需要 BigInt 的函数
也可以看看
¥See also