在 JavaScript 中,数值溢出是一个常见的问题。当我们尝试处理大数值时,JavaScript 会自动将其转换为科学计数法,导致精度丢失。这个问题可以使用 ES12 中的 BigInt 类型来解决。
BigInt 类型
BigInt 是 JavaScript 中的一种新类型,用于表示大整数。它可以表示任意大小的整数,而不会失去精度。BigInt 类型的值以 n 结尾,例如:12345678901234567890n。
如何使用 BigInt
在 JavaScript 中,我们可以使用 BigInt() 函数将数字转换为 BigInt 类型。例如:
const a = 12345678901234567890n; const b = BigInt(12345678901234567890);
BigInt 类型的值可以与普通的 Number 类型进行运算。例如:
const a = 12345678901234567890n; const b = 123; console.log(a + b); // 12345678901234567913n
需要注意的是,不能将 BigInt 类型的值与普通的字符串进行运算。例如:
const a = 12345678901234567890n; const b = "123"; console.log(a + b); // TypeError: Cannot mix BigInt and other types, use explicit conversions
BigInt 的运算符
BigInt 类型的值可以使用所有普通的算术运算符。例如:
const a = 12345678901234567890n; const b = 123; console.log(a + b); // 12345678901234567913n console.log(a - b); // 12345678901234567767n console.log(a * b); // 1518518518518518518467n console.log(a / b); // 100371141714368515n console.log(a % b); // 21n
BigInt 类型的值也可以使用位运算符。例如:
// www.javascriptcn.com code example const a = 12345678901234567890n; const b = 123; console.log(a & b); // 114n console.log(a | b); // 12345678901234567899n console.log(a ^ b); // 12345678901234567885n console.log(~a); // -12345678901234567891n console.log(a << 2n); // 49382715604938271560n console.log(a >> 2n); // 3086419725708641971n console.log(a >>> 2n); // 3086419725708641971n
BigInt 的限制
BigInt 类型的值不能与普通的 Number 类型进行混合运算。例如:
const a = 12345678901234567890n; const b = 12345678901234567890; console.log(a + b); // TypeError: Cannot mix BigInt and other types, use explicit conversions
BigInt 类型的值也不能与普通的字符串进行混合运算。例如:
const a = 12345678901234567890n; const b = "12345678901234567890"; console.log(a + b); // TypeError: Cannot mix BigInt and other types, use explicit conversions
示例代码
下面是一个使用 BigInt 类型解决数值溢出问题的示例代码:
// www.javascriptcn.com code example
function factorial(n) {
let result = 1n;
for (let i = 1n; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(100n)); // 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000n在上面的代码中,我们使用 BigInt 类型来计算阶乘。由于阶乘的结果很大,使用普通的 Number 类型会导致数值溢出。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d0f08fa941bf71342036de