JavaScript BigInt
什么是 BigInt?
在 JavaScript 中,标准的 Number
类型只能安全地表示范围在 -(2^53 - 1) 到 (2^53 - 1) 之间的整数,即大约 -9007199254740991 到 9007199254740991 之间的数值。这个限制在大多数日常应用中并不明显,但在处理非常大的整数时(如加密、时间戳的微秒表示或某些科学计算)会成为问题。
ES2020 引入了 BigInt
,这是 JavaScript 的第七种基本数据类型,专门用于表示任意精度的整数。无论多大的整数,BigInt 都能准确表示,不会有精度损失。
BigInt 的基本使用
创建 BigInt
有两种方法可以创建 BigInt:
- 在数字末尾添加
n
:
const bigNumber = 9007199254740991n;
console.log(bigNumber); // 输出: 9007199254740991n
- 使用
BigInt()
构造函数:
const anotherBigNumber = BigInt("9007199254740991");
console.log(anotherBigNumber); // 输出: 9007199254740991n
// 也可以直接传入数字
const yetAnotherBigNumber = BigInt(9007199254740991);
console.log(yetAnotherBigNumber); // 输出: 9007199254740991n
备注
当使用 BigInt()
构造函数时,你可以传入一个数字或一个表示数字的字符串。
BigInt 的表现形式
BigInt 在打印时会在末尾显示 n
,这是为了区分它与普通数字:
console.log(10n); // 输出: 10n
console.log(typeof 10n); // 输出: "bigint"
BigInt 的操作
基本算术运算
BigInt 支持大多数标准的算术运算符:
console.log(10n + 20n); // 输出: 30n
console.log(10n - 5n); // 输出: 5n
console.log(10n * 10n); // 输出: 100n
console.log(10n / 3n); // 输出: 3n (注意: 结果会向零舍入)
console.log(10n % 3n); // 输出: 1n
console.log(10n ** 3n); // 输出: 1000n (10^3)
警告
BigInt 的除法结果会向零舍入,而不是像浮点数那样提供小数部分。这是因为 BigInt 专门用于表示整数。