在 JavaScript 中,数字类型使用的是 IEEE754 规范中的 double 双精度浮点数,因此存在精度问题。当处理超出 Number.MAX_SAFE_INTEGER (9007199254740991,即 2⁵³-1)的大整数时,就会遇到精度问题。这时候就需要 BigInt 类型的出现。
ES11 引入了 BigInt 类型,它可以表示任意精度的整数,与 Number 类型不同,BigInt 类型没有范围限制,而且在进行大整数的计算时,其精度也完全保持不变。
如何使用 BigInt
BigInt 使用时需要加上 n 后缀:
const x = 9007199254740991n; // BigInt 类型
与 Number 类型不同,两者不能相互运算,需要使用 BigInt() 函数进行转换。例如:
const x = 9007199254740991n; const y = BigInt(Number.MAX_SAFE_INTEGER); console.log(x + y); // TypeError: Cannot mix BigInt and other types, use explicit conversions console.log(BigInt(x) + y); // 18014398509481982n
BigInt 相关操作
运算符
与 Number 类型不同,BigInt 类型只支持 +、-、*、/、%、**、&、|、^、<<、>>、>>> 等基本算术运算符和位运算符,并支持与运算符、相等运算符和关系运算符。
// www.javascriptcn.com code example const a = 12345678901234567890n; const b = 98765432109876543210n; console.log(a + b); // 111111111111111111100n console.log(a - b); // -86419753208641975320n console.log(a * b); // 1219326311370217956467083792238538719000n console.log(a / b); // 0n console.log(a % b); // 12345678901234567890n console.log(a ** b); // RangeError: BigInt too large console.log(a & b); // 2630029586758988416n console.log(a | b); // 109913182378624473390n console.log(a ^ b); // 107282152791865384974n console.log(a << 20n); // 12945525736376167434444800n console.log(a >> 20n); // 15185006186420n console.log(a >>> 20n); // 15185006186420n console.log(a === b); // false console.log(a !== b); // true console.log(a < b); // true console.log(a > b); // false console.log(a <= b); // true console.log(a >= b); // false
方法
BigInt 类型也提供了一些方法,如 BigInt.prototype.toString()、BigInt.prototype.valueOf() 等,与 Number 类型类似。
const x = 12345678901234567890n; console.log(x.toString()); // "12345678901234567890" console.log(x.toString(2)); // "1010101010101010110010011001100100110011110000010111010100000000" console.log(x.toLocaleString()); // "12,345,678,901,234,567,890" console.log(x.valueOf()); // 12345678901234567890n
支持的操作
在 BigInt 中,有一些之前不能在 JavaScript 中使用的操作也得以支持:
BigInt 可以被当作对象使用,支持使用 . 和 [] 运算符。
0n 和 BigInt(0) 都相当于 false 。非零值为 true。
在条件语句中,会把 BigInt 类型自动转换为 bool 类型。
const x = 12345678901234567890n;
if (x) {
console.log('BigInt 类型自动转换为 true');
}性能问题
BigInt 虽然很方便,但其性能相较于 Number 类型要差一些。正整数加速器 GMP 是基于 C 语言的,BigInt 学习的运算速度远比基于机器码的 Number 类型要慢。因此在做 Web 开发的时候,需要权衡使用场景 :)
总结
总结一下,在 JavaScript 中用 BigInt 类型处理大整数计算更为简便,同时,BigInt 可以极大地方便一些数学运算和逻辑计算的处理,如生日问题、数据加密等。同时,要意识到在性能等方面存在问题,需要根据实际情况进行选择使用。
希望本篇文章对读者有一定的学习和指导意义。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/65baaa99add4f0e0ff3325af