BigInt 是 JavaScript 中的一种数字类型,可以用来表示任意精度的整数。这意味着它可以表示大于 Number.MAX_SAFE_INTEGER
(2^53 - 1) 的整数,而不会出现精度丢失的问题。
JavaScript 的 Number
类型使用 IEEE 754 双精度浮点数格式表示,这意味着:
2^53 - 1
(即 9007199254740991
)console.log(9007199254740992 === 9007199254740993); // true,因为精度丢失
BigInt 解决了这个问题,可以表示任意大的整数。
有几种方式可以创建 BigInt:
在数字后面加 n
const bigInt = 1234567890123456789012345678901234567890n;
使用 BigInt()
函数
const bigInt = BigInt("1234567890123456789012345678901234567890");
从其他 BigInt 运算得到
const bigInt = BigInt(Number.MAX_SAFE_INTEGER) * 2n;
类型不同:BigInt 和 Number 是不同类型的值
typeof 1n; // "bigint"
typeof 1; // "number"
不能混合运算:BigInt 不能与 Number 直接进行运算
1n + 2; // TypeError: Cannot mix BigInt and other types
比较可行:BigInt 和 Number 可以比较
1n == 1; // true
1n === 1; // false (类型不同)
2n > 1; // true
转换:可以显式转换
Number(1n); // 1
BigInt(1); // 1n
BigInt 支持大多数数学运算:
// 加法
const sum = 12345678901234567890n + 98765432109876543210n;
// 减法
const difference = 10000000000n - 9999999999n;
// 乘法
const product = 123456789n * 987654321n;
// 除法 (会向下取整)
const quotient = 100n / 3n; // 33n
// 取余
const remainder = 100n % 3n; // 1n
// 指数运算
const power = 2n ** 10n; // 1024n
不能用于 Math 对象的方法
Math.sqrt(16n); // TypeError
不能与 Number 混合运算
1n + 1; // TypeError
JSON 序列化问题
JSON.stringify({ value: 1n }); // TypeError
不能使用无符号右移运算符 (>>>)
1n >>> 1n; // TypeError
function factorial(n) {
let result = 1n;
for (let i = 2n; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(100n).toString());
// 输出: 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
BigInt 是相对较新的特性,在以下环境中支持:
不支持 IE 和旧版浏览器。
BigInt 为 JavaScript 带来了处理大整数的能力,解决了 Number 类型的精度限制问题。虽然它有一些使用限制,但在需要处理大整数的场景中非常有用。使用时需要注意类型转换和兼容性问题。