-(2^53 - 1) 到 2^53 - 1,即 -9007199254740991 到 9007199254740991。const maxSafeInteger = Number.MAX_SAFE_INTEGER; // 9007199254740991
const bigIntExample = BigInt('9007199254740992');
console.log(maxSafeInteger); // 9007199254740991
console.log(bigIntExample); // 9007199254740992n
n,或者使用 BigInt 构造函数创建。const num = 42; // Number
const bigIntFromLiteral = 42n; // BigInt
const bigIntFromConstructor = BigInt(42); // BigInt
Number 类型混合运算,且不支持某些 Number 的操作(如使用 Math 对象中的函数)。const num1 = 10;
const num2 = 3;
console.log(num1 / num2); // 3.3333333333333335
const bigInt1 = 10n;
const bigInt2 = 3n;
console.log(bigInt1 / bigInt2); // 3n
// 混合运算会报错
const mixedOperation = 42n + 1; // TypeError: Cannot mix BigInt and other types
BigInt 更快,因为它使用固定大小的存储和硬件加速的运算。Math 对象中的各种函数,如 Math.sqrt、Math.sin 等。Math 对象中的大多数函数,因为这些函数针对浮点数设计。const numSqrt = Math.sqrt(16); // 4
const bigIntSqrt = Math.sqrt(16n); // TypeError: Cannot convert a BigInt value to a number
===)进行比较,但类型不同。==)进行比较,只要数值相等。const num = 42;
const bigInt = 42n;
console.log(num === bigInt); // false
console.log(num == bigInt); // true
Number 构造函数将 BigInt 转换为 Number,但可能会丢失精度。BigInt 构造函数将 Number 转换为 BigInt。const bigInt = 12345678901234567890n;
const num = Number(bigInt); // 1.2345678901234568e+19
const num2 = 42;
const bigInt2 = BigInt(num2); // 42n
Math 函数,但有精度限制。Math 函数和与 Number 类型的混合运算。选择使用哪种类型,取决于具体需求和应用场景。如果需要处理非常大的整数,且不需要浮点运算或 Math 函数,则 BigInt 是合适的选择;否则,Number 通常更合适。