ES6中BigInt的用法

557 阅读1分钟

文档

BigInt 是一个新型的内置类型,主要是为了表达大于 2^53-1 的整数。

我们定义一个 BigInt 类型的数据时有两种方式

  1. 在数字后面加 n,例如:10n。
  2. 调用 igInt()方法。
let theBigInt = 10n;
let alsoHuge = BigInt(10); //10n

当用 typeof 对其进行类型判断时,返回的是 bigint。

let theBigInt = 10n;
typeof theBigInt; // bigint

运算

  1. BigInt 支持以下的运算符,+*-**% ,并且支持除了>>> (无符号右移)之外的 其他位运算符。只能是BigInt和BigInt之间的运算。
let previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER); // 9007199254740991n 
let maxPlusOne = previousMaxSafe + 1n; // 9007199254740992n 
let maxMinusOne = previousMaxSafe - 1n; // 9007199254740990n 
let multi = previousMaxSafe * 2n; // 18014398509481982n 
let mod = previousMaxSafe % 10n; // 1n

  1. 若是BigInt和Number类型之间的运算,会报错:"Cannot mix BigInt and other types, use explicit conversions(无法混合使用 BigInt 和其他类型,需要使用显式转换)"
let previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER); // 9007199254740991n
let maxPlusOne = previousMaxSafe + 1; //throw Error
  1. BigInt 是不支持单目+运算符
+previousMaxSafe; // Uncaught TypeError: Cannot convert a BigInt value to a number

主要原因还是 BigInt 无法和 Number 类型直接运算,如果想要运算的话必须在同一个类型上,但是有一点值得注意的是,当 BigInt 转为 Number 类型时,有可能会丢失精度。

  1. 在比较运算符中,BigInt 和 Nunber 类型的之间不是严格相等的。
10n == 10; // true 
10n === 10; // false

Number 和 BigInt 是可以进行比较的。

1n < 2// true
2n > 1// true 
2n >= 2// true