跳到主要内容

BigInt 内置对象

Javascript 中可以用 Number 表示的最大数字

Number.MAX_SAFE_INTEGER // 使用 Number.MAX_SAFE_INTEGER
// 9007199254740991

const maxSafeInteger = Math.pow(2, 53) - 1; // 使用 Math.pow()
// 9007199254740991

const maxSafeIntegerBitwise = (1 << 53) - 1; // 使用位运算

const maxBigInt = BigInt(Number.MAX_SAFE_INTEGER); // 使用 BigInt
// 9007199254740991n

使用 BigInt

typeof BigInt("9007199254740991") === "bigint"; // true
typeof 1n === "bigint"; // true

不支持

  • 不能用于 Math 对象中的方法。
  • BigInt 不支持单目 (+) 运算符。
  • 不能和任何 Number 实例混合运算,两者必须转换成同一种类型。
  • BigInt 变量在转换成 Number 变量时可能会丢失精度。