简介
- 这是一个新的数据类型
- 在ES中所有的Number类型都是使用64为浮点数来进行存储,因此Number的有效值表示的最大值就是2^53。而使用新的BigInt类型可以操作任意精度的整数
例子
使用
- 一般使用的时候可以在数字字面量后面加n
- 或者使用构造函数
const bigIntNum = 9999999999999999999999999999999999n
const bigIntNum2 = BigInt(9999999999999999999999999999999999)
console.log(bigIntNum,bigIntNum2); // 9999999999999999999999999999999999n 9999999999999999455752309870428160n
// 数据过大的时候,使用Bigint构造函数,我们应该用字符串表示
const bigIntNum3 = BigInt("9999999999999999999999999999999999")
console.log(bigIntNum3);
运算
同类型运算
支持+、-、*、/、**
的操作
console.log(3n + 2n); // 5n
console.log(3n * 2n); // 6n
console.log(3n - 2n); // 1n
console.log(3n / 2n); // 1n
console.log(3n ** 2n); // 9n
我们会发现BigInt进行运算最终得到的都是整数,比如3n / 2n
,最终得到的是1n
,他支持的是向下取整
不同类型计算
字符串
字符串,他可以和字符串之间进行 + 号操作
console.log(2n + "hello"); // 2hello
console.log("world" + 3n); // world3
number
- BigInt不能和Number一起运算,会抛出类型错误
console.log(2 + 2n); // Cannot mix BigInt and other types, use explicit conversions
- 一些内置的数字处理的模块不支持对于BigInt处理
Math.pow(2n) // Cannot convert a BigInt value to a number
- BigInt与Number相等,但不是严格相等
console.log(2 == 2n); // true
console.log(2 === 2n); // false
- 可以比较大小
console.log(3n < 4); // true
console.log(4n > 3); // true
- 布尔值转化
console.log(!!0n); // false
console.log(!!1n); // true
- Number与BigInt转化,两者智能通过构造函数进行转换
console.log(Number(1n)); // 1
console.log(BigInt(1)); // 1n
兼容性
BigInt
数据类型只在一下浏览器支持
- Chrome 67+
- FIrefox 68+
- Safari 14+
- Node.js 12+
因为他是基本的数据类型,目前没有完整的兼容库来支持无法兼容的浏览器