← 中文资源

简体中文版本

BigInt 承接安全整数范围之外

整数超出 Number.MAX_SAFE_INTEGER 后换 BigInt:加减精确无损、与 Number 混算抛 TypeError、显式转换后恢复运算。

阅读英文原文

实现说明

limit、productId 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 每一步打印都带着自己的标签:safe limit:、number distorts:、bigint exact:。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。 跨调用保留的状态放在这些顶层绑定里:limit、productId。

核心语句

const limit = Number.MAX_SAFE_INTEGER;
const productId = 9007199254740993n;

代码示例

const limit = Number.MAX_SAFE_INTEGER;
console.log('safe limit:', limit);

// 超出安全区间的 Number 会失真:相邻两个数加出来相等
console.log('number distorts:', limit + 1 === limit + 2);
console.log('bigint exact:', BigInt(limit) + 1n === BigInt(limit) + 2n);

const productId = 9007199254740993n;
console.log('id as number:', Number(productId));
console.log('id as bigint:', productId.toString());

// BigInt 与 Number 不能直接混合运算,先显式转换
try {
  1n + 1;
} catch (error) {
  console.log('mixing throws TypeError:', error instanceof TypeError);
}
console.log('explicit convert:', 1n + BigInt(1));