Skip to content

Bigint

BigInt 是一种特殊的数字类型,它提供了对任意长度整数的支持。

js
// 创建方式1 : Number + n
const bigint = 1234567890123456789012345678901234567890n;

// 创建方式2 : 使用 BigInt()
const sameBigint = BigInt("1234567890123456789012345678901234567890");

10n === BigInt(10); // true

运算

js
1n + 2n; // 3n

5n / 2n; // 2n,除法 5/2 的结果向零进行舍入

Bigint 不能和 Number 混合运算。

js
1n + 2; // Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions

但是可以手动转换

js
Number(1n); // 超过部分会截取。

// 不支持 一元
+1n; // Uncaught TypeError: Cannot convert a BigInt value to a number

比较

js
1 == 1n; // true
1 === 1n; // false
js
2n > 1; // true
2n > 3; // false

boolean 的 的行为类似 number

js
0n ? "真" : "假"; // 假

100n ? "真" : "假"; // 真

toJSON

BigInt 并没有官方的处理,这里需要自己决定

推荐使用 String 的形式

js
BigInt.prototype.toJSON = function () {
  return this.toString();
};