🚀 参考链接

  • 阮大大:数值的扩展
  • MDN:Bigint

    Bigint 是什么?

    bigint 是 ES2020 引入的新的数据类型,顾名思义,他主要用来表示大整数,并且没有位数的限制,任何位数的整数都可以精确表示。

    为什么引入了 Bigint?

    在 Bigint 出现之前,我们都是用 Number 来表示 JS 中的数字,Number 遵循 IEEE754 标准实现,JavaScript 所有数字都保存成双精度 64 位浮点数,这给数值的表示带来了两大限制:
  1. 一是数值的精度只能到 53 个二进制位(相当于 16 个十进制位),大于这个范围的整数,JavaScript 是无法精确表示的,这使得 JavaScript 不适合进行科学和金融方面的精确计算。
  2. 大于或等于2的1024次方的数值,JavaScript 无法表示,会返回Infinity


  1. // 超过 53 个二进制位的数值,无法保持精度
  2. Math.pow(2, 53) === Math.pow(2, 53) + 1 // true
  3. // 超过 2 的 1024 次方的数值,无法表示
  4. Math.pow(2, 1024) // Infinity

扩展阅读

  • IEEE754 标准

    怎么使用?

    基本使用

    为了和 Number 类型区分,Bigint 类型的数据必须添加后缀 n。 ```javascript // 基本使用 —

const a = 1n; const b = 2n;

a + b; // 3n

// 大位数运算 —

const a = 2172141653n; const b = 15346349309n;

// BigInt 可以保持精度 a * b // 33334444555566667777n

// 普通整数无法保持精度 Number(a) * Number(b) // 33334444555566670000

  1. <a name="3dz3f"></a>
  2. ## 其他进制
  3. ```javascript
  4. 0b1101n // 二进制
  5. 0o777n // 八进制
  6. 0xFFn // 十六进制

使用时需要注意什么?

不能与普通的 Number 一起使用

  1. // 与 Number 类型判断是否相等时的问题。
  2. 42n === 42 // false
  3. // bigint 不能与 number 进行数值运算,以下写法都会报错:Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
  4. 1n + 1;
  5. 1n - 1;
  6. 1n * 1;
  7. 1n / 1;
  8. 1n % 1;

typeof

  1. typeof 123n // 'bigint'

不能使用正号(+)

  1. 可以使用负号(-),但是不能使用正号(+),因为会与 asm.js 冲突。
  2. -42n // 正确
  3. +42n // 报错

不能表示小数

  1. bigint 做除法运算时会去掉小数部分
  2. 9n / 5n; // 1n

在 JSON 中使用

对任何 BigInt 值使用 JSON.stringify() 都会引发 TypeError,因为默认情况下 BigInt 值不会在 JSON 中序列化。

  1. JSON.stringify({a: 1n}); // Uncaught TypeError: Do not know how to serialize a BigInt

但是,如果需要,可以实现 toJSON 方法:

  1. BigInt.prototype.toJSON = function() { return this.toString(); }
  2. JSON.stringify({a: 1n}); // "{"a":"1"}"

与其他类型的转换

  1. BigInt(123) // 123n
  2. BigInt('123') // 123n
  3. BigInt(false) // 0n
  4. BigInt(true) // 1n
  5. new BigInt() // TypeError
  6. BigInt(undefined) //TypeError
  7. BigInt(null) // TypeError
  8. BigInt('123n') // SyntaxError
  9. BigInt('abc') // SyntaxError
  10. BigInt(1.5) // RangeError
  11. BigInt('1.5') // SyntaxError
  12. Boolean(0n) // false
  13. Boolean(1n) // true
  14. Number(1n) // 1
  15. String(1n) // "1"
  16. !0n // true
  17. !1n // false
  18. 0n < 1 // true
  19. 0n < true // true
  20. 0n == 0 // true
  21. 0n == false // true
  22. 0n === 0 // false
  23. '' + 123n // "123"

静态方法

BigInt.asIntN()

将 BigInt 值转换为一个 -2 与 2-1 之间的有符号整数。

BigInt.asUintN()

将一个 BigInt 值转换为 0 与 2-1 之间的无符号整数。