简介

BigInt数据类型的目的是比Number数据类型支持的范围更大的整数值。在对大整数执行数学运算时,以任意精度表示整数的能力尤为重要。使用BigInt,整数溢出将不再是问题

使用:

要创建BigInt,只需在整数的末尾追加n即可。比较:

  1. console.log(9007199254740995n); // → 9007199254740995n
  2. console.log(9007199254740995); // → 9007199254740996

或者,可以调用BigInt()构造函数

BigInt("9007199254740995");    // → 9007199254740995n

注意:

除一元加号(+)运算符外,所有算术运算符都可用于BigInt

10n + 20n;    // → 30n
10n - 20n;    // → -10n
+10n;         // → TypeError: Cannot convert a BigInt value to a number
-10n;         // → -10n
10n * 20n;    // → 200n
20n / 10n;    // → 2n
23n % 10n;    // → 3n
10n ** 3n;    // → 1000n

请记住,不能使用严格相等运算符将BigInt与常规数字进行比较,因为它们的类型不同:

console.log(10n === 10);    // → false
console.log(typeof 10n);    // → bigint
console.log(typeof 10);     // → number

js的8种数据类型

  • Boolean
  • Null
  • Undefined
  • Number
  • BigInt
  • String
  • Symbol
  • Object