BigInt小结

1,969 阅读1分钟

每天做个总结吧,坚持就是胜利!

    /**
        @date 2021-06-06
        @description BigInt小结
    */

壹(序)

JavaScript的基本数据类型Number只能安全存储-(2 ** 53 - 1)2 ** 53 - 1(包含边界)的值;

安全存储指的是能正确的区分两个值是否相等,比如JavaScript中2 ** 54 + 1 === 2 ** 54 + 2true,但是很显然这在数学上是不对的,为了能正确的存储所有的值,ES2020引入了BigInt,可以安全的存储任意的整数;

console.log(2 ** 54 + 1 === 2 ** 54 + 2); // true
console.log(BigInt(2 ** 54) + 1n === BigInt(2 ** 54) + 2n); // false

贰(使用)

BigInt的使用有以下两种方法:

  1. Number类型的整数后面加上n;如10n
  2. 使用函数BigInt();如BigInt(10)

叁(注意点)

  1. BigInt只能表示整数;
10.0n; // Uncaught SyntaxError: Invalid or unexpected token
(10.0)n; // Uncaught SyntaxError: Unexpected identifier
  1. BigInt不能与Number类型进行计算操作;
10 + 10n; // Uncaught TypeError: Cannot mix BigInt and other types
  1. BigInt的toString方法和Number的toString方法一样,可以传一个radius,用于转换进制
console.log(10n.toString(2)); // '1010'
  1. 使用/对BigInt类型的整数进行计算操作时,会自动忽略小数部分;
10n / 6n; // 1n
10n / 3n; // 3n
  1. BigInt无法使用Math中的方法;
Math.max(10n, 20n, 30n); // Uncaught TypeError: Cannot convert a BigInt value to a number
  1. BigInt无法使用JSON.stringify方法;
JSON.stringify(10n); // Uncaught TypeError: Do not know how to serialize a BigInt

肆(引申)

如何正确的使用JSON.stringify方法:

实现BigInt的toJSON方法:

BigInt.prototype.toJSON = function () {
    return this.toString();
};

console.log(JSON.stringify(10n)); // '10'