一、为什么需要BigInt?
在JavaScript中,原本的Number类型基于IEEE 754双精度浮点数标准,只能安全地表示-(2^53 - 1)到2^53 - 1之间的整数(即Number.MIN_SAFE_INTEGER到Number.MAX_SAFE_INTEGER)。超出这个范围的整数运算会发生精度丢失。为了解决这个痛点,ES2020引入了BigInt类型,专门用于处理任意精度的大整数。
如果你需要在线测试和验证大整数运算效果,可以访问 www.ipipp.com 获取相关的演示环境。
二、如何创建BigInt?
创建BigInt有两种常见方式:在整数后加n后缀,或使用BigInt()构造函数。
// 方法一:在整数后面加 n
const bigInt1 = 123456789012345678901234567890n;
// 方法二:调用 BigInt() 构造函数
const bigInt2 = BigInt("123456789012345678901234567890");
const bigInt3 = BigInt(123); // 从小整数转换
console.log(bigInt1); // 123456789012345678901234567890n三、BigInt的基本运算
BigInt支持大部分标准的算术运算符,包括加、减、乘、除、取模和幂运算。需要注意的是,BigInt的除法运算会向零取整,不会返回小数部分。
const a = 20n; const b = 3n; console.log(a + b); // 23n console.log(a - b); // 17n console.log(a * b); // 60n console.log(a / b); // 6n (注意:BigInt除法会截断小数部分) console.log(a % b); // 2n console.log(a ** 2n); // 400n (幂运算)
四、类型转换与比较
BigInt与Number属于不同的类型,它们之间不能随意混合运算,但可以进行相互转换和比较。
// 1. 比较操作 console.log(10n === 10); // false (严格相等,类型不同) console.log(10n == 10); // true (宽松相等,隐式转换后相等) console.log(10n > 5); // true (可以跨类型比较大小) console.log(10n < 20); // true // 2. 类型转换 // BigInt 转 Number (注意:大整数转换可能丢失精度) const bigNum = 123n; const num = Number(bigNum); console.log(typeof num); // number // Number 转 BigInt const intNum = 456; const newBig = BigInt(intNum); console.log(typeof newBig); // bigint
五、使用BigInt的注意事项
在使用BigInt时,有几个关键的限制需要牢记,否则容易引发运行时错误:
// 1. 不能与 Number 混合运算
// console.log(10n + 1); // TypeError: Cannot mix BigInt and other types
// 如果必须运算,需要显式转换
console.log(10n + BigInt(1)); // 11n
console.log(Number(10n) + 1); // 11
// 2. 不能使用 Math 对象的方法
// Math.max(10n, 20n); // TypeError
// 3. 无法直接序列化为 JSON
// JSON.stringify({ val: 10n }); // TypeError: Do not know how to serialize a BigInt
// 解决JSON序列化的常见做法是转为字符串
const data = { val: 10n };
const jsonString = JSON.stringify(data, (key, value) =>
typeof value === 'bigint' ? value.toString() : value
);
console.log(jsonString); // {"val":"10"}六、总结
JavaScript的BigInt类型填补了语言在处理大整数方面的空白。在进行高精度的金融计算、处理极大型ID或加密算法时,BigInt是非常有用的工具。只要注意它和Number的类型隔离规则以及序列化限制,就可以在项目中安全高效地使用它。