在 JavaScript 中,处理数值是一项常见的任务。然而,在 ES2020 之前,JavaScript 只有一种数值类型——Number
,它遵循 IEEE 754 双精度 64 位浮点数标准,这就导致它能精确表示的整数范围是有限的。为了解决这个问题,ES2020 引入了一种新的原始数据类型:BigInt
,它可以表示任意大的整数。
n
在数字后面直接添加 n
就可以将其转换为 BigInt
类型。
const bigIntNum = 12345678901234567890n;
console.log(typeof bigIntNum); // 输出: "bigint"
BigInt()
构造函数也可以使用 BigInt()
函数将其他类型的值转换为 BigInt
。
const num = 123;
const bigIntFromNum = BigInt(num);
console.log(bigIntFromNum); // 输出: 123n
const str = "98765432109876543210";
const bigIntFromString = BigInt(str);
console.log(bigIntFromString); // 输出: 98765432109876543210n
BigInt
支持常见的数学运算,包括加法(+
)、减法(-
)、乘法(*
)、除法(/
)、取余(%
)和幂运算(**
)。
const a = 10n;
const b = 20n;
const sum = a + b;
console.log(sum); // 输出: 30n
需要注意的是,BigInt
除法会向下取整。
const dividend = 15n;
const divisor = 2n;
const quotient = dividend / divisor;
console.log(quotient); // 输出: 7n
const base = 2n;
const exponent = 10n;
const result = base ** exponent;
console.log(result); // 输出: 1024n
BigInt
可以使用比较运算符(如 <
、>
、<=
、>=
、==
、===
)进行比较。
const x = 10n;
const y = 20n;
console.log(x < y); // 输出: true
console.log(x === 10n); // 输出: true
Number
类型的区别Number
类型在处理大整数时会出现精度丢失的问题,而 BigInt
可以精确表示任意大的整数。
const largeNumber = 9007199254740991;
const largeNumberPlusOne = largeNumber + 1;
console.log(largeNumber === largeNumberPlusOne); // 输出: true
const largeBigInt = 9007199254740991n;
const largeBigIntPlusOne = largeBigInt + 1n;
console.log(largeBigInt === largeBigIntPlusOne); // 输出: false
BigInt
和 Number
类型不能直接进行混合运算,需要先进行类型转换。
const num = 10;
const bigInt = 20n;
// 以下代码会报错
// const wrongResult = num + bigInt;
const correctResult = BigInt(num) + bigInt;
console.log(correctResult); // 输出: 30n
在加密算法中,经常需要处理非常大的整数,BigInt
可以满足这种需求。
金融领域的计算可能涉及到非常大的金额,使用 BigInt
可以避免精度丢失。
特性 | 描述 |
---|---|
创建方式 | 可以使用后缀 n 或 BigInt() 构造函数 |
基本运算 | 支持加法、减法、乘法、除法、取余和幂运算 |
比较运算 | 可以使用常见的比较运算符 |
与 Number 区别 |
Number 有精度限制,BigInt 可精确表示大整数;两者不能直接混合运算 |
应用场景 | 加密算法、金融计算等 |
BigInt
为 JavaScript 处理大整数提供了强大的支持,在需要精确表示大整数的场景中,它是一个非常有用的工具。开发者在使用时需要注意其与 Number
类型的区别,避免出现类型不匹配的错误。