HLJ 发布于
2025-06-11 11:45:22
0阅读

JavaScript BigInt 详解与应用

上一篇文章:

JavaScript引用类型详解

JavaScript BigInt 详解

BigInt 是 JavaScript 中的一种数字类型,可以用来表示任意精度的整数。这意味着它可以表示大于 Number.MAX_SAFE_INTEGER (2^53 - 1) 的整数,而不会出现精度丢失的问题。

为什么需要 BigInt

JavaScript 的 Number 类型使用 IEEE 754 双精度浮点数格式表示,这意味着:

  1. 它能安全表示的最大整数是 2^53 - 1 (即 9007199254740991)
  2. 超过这个值后,整数运算可能会失去精度
console.log(9007199254740992 === 9007199254740993); // true,因为精度丢失

BigInt 解决了这个问题,可以表示任意大的整数。

创建 BigInt

有几种方式可以创建 BigInt:

  1. 在数字后面加 n

    const bigInt = 1234567890123456789012345678901234567890n;
    
  2. 使用 BigInt() 函数

    const bigInt = BigInt("1234567890123456789012345678901234567890");
    
  3. 从其他 BigInt 运算得到

    const bigInt = BigInt(Number.MAX_SAFE_INTEGER) * 2n;
    

BigInt 的特性

  1. 类型不同:BigInt 和 Number 是不同类型的值

    typeof 1n; // "bigint"
    typeof 1;  // "number"
    
  2. 不能混合运算:BigInt 不能与 Number 直接进行运算

    1n + 2; // TypeError: Cannot mix BigInt and other types
    
  3. 比较可行:BigInt 和 Number 可以比较

    1n == 1; // true
    1n === 1; // false (类型不同)
    2n > 1; // true
    
  4. 转换:可以显式转换

    Number(1n); // 1
    BigInt(1); // 1n
    

BigInt 运算

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

BigInt 的限制

  1. 不能用于 Math 对象的方法

    Math.sqrt(16n); // TypeError
    
  2. 不能与 Number 混合运算

    1n + 1; // TypeError
    
  3. JSON 序列化问题

    JSON.stringify({ value: 1n }); // TypeError
    
  4. 不能使用无符号右移运算符 (>>>)

    1n >>> 1n; // TypeError
    

实际应用场景

  1. 大整数计算:金融、密码学等领域需要精确的大整数计算
  2. 高精度时间戳:处理纳秒级时间戳
  3. 大ID处理:如Twitter的雪花算法生成的ID
  4. 数学计算:大数阶乘、斐波那契数列等

示例:计算大数阶乘

function factorial(n) {
  let result = 1n;
  for (let i = 2n; i <= n; i++) {
    result *= i;
  }
  return result;
}

console.log(factorial(100n).toString());
// 输出: 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

浏览器兼容性

BigInt 是相对较新的特性,在以下环境中支持:

  • Node.js: 10.4.0 及以上
  • Chrome: 67 及以上
  • Firefox: 68 及以上
  • Safari: 14 及以上
  • Edge: 79 及以上

不支持 IE 和旧版浏览器。

总结

BigInt 为 JavaScript 带来了处理大整数的能力,解决了 Number 类型的精度限制问题。虽然它有一些使用限制,但在需要处理大整数的场景中非常有用。使用时需要注意类型转换和兼容性问题。

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2025-06-11/845.html
最后生成于 2025-06-13 16:39:21
上一篇文章:

JavaScript引用类型详解

此内容有帮助 ?
0