一,BigInt定义
BigInt是ES11引入的新的基本数据类型, 它可以表示任意精度格式的整数,使用BigInt可以安全的存储和操作大整数,即使这个数已经超出了Number能够表示的安全整数范围。解决了之前Number整数溢出的问题。
二,创建BigInt
有两种方式
(1):直接在一个整数字面量后面加n
(2):通过BigInt(value)其中value表示创建对象的数值, 可以是字符串或者整数(!!!注意:BigInt不是构造函数,因此不能使用new操作符)
let val1 = 10n;
let val2 = BigInt(10);
let val3 = BigInt('5');
console.log(val1 === val2);//true
console.log(val1, val2, val3);//10n 10n 5n
三, 类型判断
(1):通过typeof 操作符来判断是否为BigInt类型(返回字符串"bigint")
(2):通过Object.prototype.toString方法判断(返回字符串"[object BigInt]")
console.log(typeof val1, typeof val2, typeof val3);//bigint bigint bigint
console.log(Object.prototype.toString.call(val1), Object.prototype.toString.call(val2), Object.prototype.toString.call(val3))
//[object BigInt] [object BigInt] [object BigInt]
四,运算
(1):可以将普通整数值转化为大整形的值(BigInt)(注: 不能使用浮点数进行转换)
let n = 1;
console.log(BigInt(1n));//1n
console.log(BigInt(0.2));
(2):BigInt数据类型不能直接和普通数据类型进行运算,两者必须转换成同一种类型, 不能用与 Math 对象中的方法
// 超过number的最大数值范围,运算就会出错
let max = Number.MAX_SAFE_INTEGER;//Number的最大安全整数
console.log(max + 1 === max + 2);//true
console.log(BigInt(10) + 1n);//11n
console.log(BigInt(max) + 1);
(3):BigInt和Number不是严格相等的, 是宽松相等的
console.log(BigInt(10) === 10);//false
console.log(BigInt(10) == 10);//true
(4):Number 和 BigInt 可以进行比较
console.log(2n > 2);//false
console.log(2n > 1);//true
console.log(2n >= 2);//true
console.log(2n < 3);//true
console.log(2n < 2);//false
console.log(2n <= 2);//true
(5):BigInt和String进行转换时, 其标志性的n会被省略
console.log(String(10n), typeof String(10n));//'10' string
console.log(10n + '', typeof (10n + ''));//'10' string
(6):BigInt 没有 Number 的正零(+0)和负零(-0)之分,因为BigInt 表示的是整数