Skip to content

新的原始数据类型:BigInt,表示一个任意精度的整数,可以表示超长数据,可以超出2的53次方。

javascript
// js 中 Number类型只能安全的表示-(2^53-1)至 2^53-1 范的值
console.log(2 ** 53) // 9007199254740992
console.log(Number.MAX_SAFE_INTEGER) // 9007199254740991

BigInt

javascript
const bigInt = 9007199254740993n
console.log(bigInt) // 9007199254740993n
console.log(typeof bigInt) // bigint

console.log(1n == 1) // true
console.log(1n === 1) // false

const bigIntNum = BigInt(9007199254740993n)
console.log(bigIntNum) // 9007199254740993n

Bigint和Number的区别

Number类型的数字有精度限制,数值的精度只能到 53 个二进制位(相当于 16 个十进制位, 正负9007199254740992),大于这个范围的整数,就无法精确表示了。 Bigint没有位数的限制,任何位数的整数都可以精确表示。但是其只能用于表示整数,且为了与Number进行区分,BigInt 类型的数据必须添加后缀n。BigInt 可以使用负号(-),但是不能使用正号(+)。 另外number类型的数字和Bigint类型的数字不能混合计算。

javascript
console.log(12n + 12)

// Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions at <anonymous>:1:16