类型错误:无法将 BigInt 转换为数字
当算术运算涉及 BigInt
和 Number
值的混合时,会发生 JavaScript 异常 "无法将 BigInt 转换为数字"。
¥The JavaScript exception "can't convert BigInt to number" occurs when an arithmetic operation involves a mix of BigInt
and Number
values.
信息
¥Message
TypeError: Cannot convert a BigInt value to a number (V8-based) TypeError: Cannot mix BigInt and other types, use explicit conversions (V8-based) TypeError: BigInts have no unsigned right shift, use >> instead (V8-based) TypeError: can't convert BigInt to number (Firefox) TypeError: Conversion from 'BigInt' to 'number' is not allowed. (Safari) TypeError: Invalid mix of BigInt and other type in addition/multiplication/…. (Safari) TypeError: BigInt does not support >>> operator (Safari)
错误类型
什么地方出了错?
¥What went wrong?
算术运算符的两侧必须都是 BigInt,或者都不是。如果运算涉及 BigInt 和数字的混合,则结果应该是 BigInt 还是数字是不明确的,因为在这两种情况下都可能会损失精度。
¥The two sides of an arithmetic operator must both be BigInts or both not. If an operation involves a mix of BigInts and numbers, it's ambiguous whether the result should be a BigInt or number, since there may be loss of precision in both cases.
当 BigInt 通过 数字强制 过程隐式转换为数字时,也会发生错误。例如,如果将 BigInt 传递给需要数字的内置方法。
¥The error also happens when a BigInt is implicitly converted to a number via the number coercion process. For example, if a BigInt is passed to a built-in method that expects a number.
如果在两个 BigInt 之间使用 无符号右移运算符 (>>>
),也可能会发生该错误。在 Firefox 中,消息是相同的:"无法将 BigInt 转换为数字"。
¥The error can also happen if the unsigned right shift operator (>>>
) is used between two BigInts. In Firefox, the message is the same: "can't convert BigInt to number".
示例
在运算中混合数字和 BigInt
在 BigInt 上使用无符号右移
也可以看看
¥See also