每天做个总结吧,坚持就是胜利!
/**
@date 2021-06-06
@description BigInt小结
*/
壹(序)
JavaScript的基本数据类型Number只能安全存储-(2 ** 53 - 1)到2 ** 53 - 1(包含边界)的值;
安全存储指的是能正确的区分两个值是否相等,比如JavaScript中2 ** 54 + 1 === 2 ** 54 + 2为true,但是很显然这在数学上是不对的,为了能正确的存储所有的值,ES2020引入了BigInt,可以安全的存储任意的整数;
console.log(2 ** 54 + 1 === 2 ** 54 + 2); // true
console.log(BigInt(2 ** 54) + 1n === BigInt(2 ** 54) + 2n); // false
贰(使用)
BigInt的使用有以下两种方法:
- 在
Number类型的整数后面加上n;如10n; - 使用函数
BigInt();如BigInt(10);
叁(注意点)
- BigInt只能表示
整数;
10.0n; // Uncaught SyntaxError: Invalid or unexpected token
(10.0)n; // Uncaught SyntaxError: Unexpected identifier
BigInt不能与Number类型进行计算操作;
10 + 10n; // Uncaught TypeError: Cannot mix BigInt and other types
- BigInt的
toString方法和Number的toString方法一样,可以传一个radius,用于转换进制;
console.log(10n.toString(2)); // '1010'
- 使用
/对BigInt类型的整数进行计算操作时,会自动忽略小数部分;
10n / 6n; // 1n
10n / 3n; // 3n
- BigInt无法使用
Math中的方法;
Math.max(10n, 20n, 30n); // Uncaught TypeError: Cannot convert a BigInt value to a number
- 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'