Make a summary every day, persistence is victory!

/** @date 2021-06-06 @description BigInt */Copy the code

One (sequence)

JavaScript’s basic data type Number can only safely store values from -(2 ** 53-1) to 2 ** 53-1 (including boundaries);

For example, in JavaScript 2 ** 54 + 1 === 2 ** 54 + 2 is true, but this is not mathematically correct. In order to store all values correctly, ES2020 introduced BigInt. Can safely store arbitrary integers;

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

Ii (Use)

BigInt can be used in two ways:

  1. inNumberType followed by the integern; Such as10n;
  2. Using the functionBigInt(); Such asBigInt(10);

Three (Attention points)

  1. BigInt can only representThe integer;
10.0 n; // Uncaught SyntaxError: Invalid or unexpected token (10.0)n; // Uncaught SyntaxError: Unexpected identifierCopy the code
  1. BigIntCan’t withNumbertypeTo calculateOperation;
10 + 10n; // Uncaught TypeError: Cannot mix BigInt and other types
Copy the code
  1. BigInt,toStringThe toString method is the same as Number’s toString methodradiusforTransformation into the system;
console.log(10n.toString(2)); / / '1010'Copy the code
  1. use/The calculation operation on an integer of type BigInt is automatically performedIgnore the decimalPart;
10n / 6n; // 1n
10n / 3n; // 3n
Copy the code
  1. BigInt cannot be usedMathMethod in;
Math.max(10n, 20n, 30n); // Uncaught TypeError: Cannot convert a BigInt value to a number
Copy the code
  1. BigInt cannot be usedJSON.stringifyMethods;
JSON.stringify(10n); // Uncaught TypeError: Do not know how to serialize a BigInt
Copy the code

Iv (Extended)

How to use the json.stringify method correctly:

ToJSON for BigInt

BigInt.prototype.toJSON = function () { return this.toString(); }; console.log(JSON.stringify(10n)); / / '10'Copy the code