BigInt 的使用场景
BigInt 是 JavaScript 在 ES2020 中引入的一种新数据类型,专门用于处理超过 Number 类型安全整数范围的大整数。在某些特定场景中,BigInt 是非常有用的:
-
处理超大整数:
Number类型只能安全表示在范围为-(2^53 - 1)到(2^53 - 1)之间的整数(约为±9007199254740991),超出这个范围的整数运算会导致精度丢失。而BigInt可以表示任意长度的整数,适用于需要高精度整数计算的场景,例如:- 科学计算、金融计算等对精度要求极高的领域。
- 加密算法、大数运算(如区块链的数字签名和哈希运算)。
-
避免精度丢失:在涉及超出
Number类型安全范围的数值时,使用BigInt可以确保数值运算的精度。例如:const bigIntNumber = 9007199254740991n; // 超出安全范围的整数 const result = bigIntNumber + 10n; // BigInt 运算仍保持精度 console.log(result); // 9007199254741001n -
处理超出范围的整数字符串:有时我们需要处理表示非常大的数字的字符串,直接使用
BigInt可以有效转换这些字符串,并进行安全的计算:const bigIntFromString = BigInt("1234567890123456789012345678901234567890"); console.log(bigIntFromString); // 1234567890123456789012345678901234567890n
BigInt 的使用方法
-
创建 BigInt
-
通过在数字后面添加
n来直接定义一个BigInt数值:const bigIntValue = 1234567890123456789012345678901234567890n; -
使用
BigInt()构造函数,可以将数字或字符串转换为BigInt:const bigIntFromNumber = BigInt(123); // 123n const bigIntFromString = BigInt("12345678901234567890"); // 12345678901234567890n
-
-
BigInt 的运算
-
BigInt支持常见的运算符(+,-,*,/,%,**),但运算结果仍然是BigInt,即所有参与运算的值都必须是BigInt类型:const big1 = 100n; const big2 = 20n; console.log(big1 + big2); // 120n console.log(big1 * big2); // 2000n -
注意: 除法运算会向下取整,因为
BigInt是整数类型,没有小数:console.log(10n / 3n); // 3n
-
-
与
Number的转换-
不能直接将
BigInt和Number混合运算,如果尝试这么做会抛出错误:const bigIntValue = 100n; const numberValue = 50; console.log(bigIntValue + numberValue); // 报错:Cannot mix BigInt and other types -
你可以显式地将
BigInt和Number互相转换:const bigIntValue = 100n; const numberValue = 50; const result = bigIntValue + BigInt(numberValue); // 转换 number 为 BigInt console.log(result); // 150n const convertedToNumber = Number(bigIntValue); // 转换 BigInt 为 Number console.log(convertedToNumber); // 100
-
-
BigInt 与 JSON
BigInt不能直接存储在JSON对象中,因为JSON不支持BigInt。你可以在序列化时转换为字符串:const obj = { bigValue: 12345678901234567890n }; const jsonString = JSON.stringify(obj, (key, value) => typeof value === 'bigint' ? value.toString() : value ); console.log(jsonString); // {"bigValue":"12345678901234567890"}
使用 BigInt 的注意事项
BigInt只适用于整数运算,不适用于浮点数或小数的计算。- 在某些性能敏感的场合,如大规模科学计算中,
BigInt的性能可能会低于Number,因此需要根据场景选择合适的数据类型。
986

被折叠的 条评论
为什么被折叠?



