BigInt 数据类型
JavaScript 中的 BigInt 数据类型是一种数字原始值,可以表示具有任意大小的整数。这与 Number 数据类型相反,Number 数据类型仅限于表示 -(253 - 1) 和 253 - 1 之间的整数。
为动态 Web 应用程序提供支持的 JavaScript 传统上根据广泛采用的 IEEE-754 标准的双精度浮点格式使用 Number 类型进行数字表示。这个标准施加了一个重要的限制:它只能精确地表示最多 253 - 1 作为其最大安全整数。但是,超过此数值阈值会开始侵蚀数值的保真度,并在关键计算中引入潜在的不准确之处。
JavaScript 引入了 BigInt 数据类型来响应这些限制;顾名思义,BigInt 解决了有限精度的缺点。事实证明,这种能力在各种场景中都是不可或缺的,特别是在密码算法、金融计算和要求最高精度的复杂数学运算等领域:它允许以任意精度表示整数,这是一个重大进步。
声明和初始化
您可以使用数字文本后跟 n 后缀或使用 BigInt() 构造函数创建 BigInt。
const bigIntLiteral = 123n;
const anotherBigInt = BigInt(456);
请务必注意,尝试在不进行显式转换的情况下混合使用常规数字和 BigInt 可能会导致错误。
基本操作
BigInt 支持标准算术运算,如加法、减法、乘法和除法。执行操作时,两个操作数都必须是 BigInt 类型。
const a = 123n;
const b = 456n;
const sum = a + b; // 579n
const product = a * b; // 56088n
比较
BigInt 值可以使用标准比较运算符进行比较,例如 <、>、<=、>= 和 ===。
const a = 123n;
const b = 456n;
a > b; // false
a === b; // false
转换
可以在 BigInt 和常规数字之间进行转换,但请记住,对于非常大的 BigInt 值,可能会损失精度。
const bigIntValue = BigInt("12345678901234567890");
const regularNumber = Number(bigIntValue);
const bigIntValue = BigInt("12345678901234567890");
const regularNumber = Number(bigIntValue);
例子
示例 1:简单的 BigInt 算术
在此示例中,我们演示了 2 个 BigInt 数字 num1 和 num2 的加法和乘法,其值分别为 123n 和 456n。通过实现大整数值的准确表示而不冒精度损失的风险,BigInt 克服了常规 JavaScript 数字中的潜在缺点。
<!DOCTYPE html>
<html>
<body>
<h2>Simple BigInt Arithmetic</h2>
<p id="result"></p>
<script>
const num1 = 123n;
const num2 = 456n;
const sum = num1 + num2;
const product = num1 * num2;
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("result").innerText =
`Sum of ${num1} & ${num2} is ${sum} and their product: ${product}`;
});
</script>
</body>
</html>
示例 2:使用 BigInt 的斐波那契数列生成器
斐波那契数列:一系列数字,其中每个数字都是其前两个数字的总和;使用 BigInt 处理超出常规 JavaScript 数字精度限制的较大值。通过 generateFibonacci 函数,数组用作这些序列值的存储,即使对于具有大量数值大小的术语,也能保证精确计算。
<!DOCTYPE html>
<html>
<body>
<h2>Fibonacci Sequence</h2>
<p id="result"></p>
<script>
function generateFibonacci(n) {
const sequence = [0n, 1n];
for (let i = 2; i <= n; i++) {
sequence[i] = sequence[i - 1] + sequence[i - 2];
}
return sequence;
}
document.addEventListener("DOMContentLoaded", function () {
const result = generateFibonacci(20);
document.getElementById("result").innerText = "Fibonacci Sequence of 1st 20 terms: " + result.join(", ");
});
</script>
</body>
</html>
示例 3:使用 BigInt 的阶乘计算器
阶乘是小于或等于该数字的所有正整数的乘积。为了找到阶乘,我们使用了 BigInt。对于像5和10这样的小数字,常规数字可以工作,但是当我们必须找到10000的阶乘时会发生什么,输出就会太大。因此,BigInt 会来拯救我们。在这个例子中,我们在循环的帮助下找到 20n 的阶乘。
<!DOCTYPE html>
<html>
<body>
<h2>Factorial of a Large Number</h2>
<p id="result"></p>
<script>
function calculateFactorial() {
const num = 20n; // Calculate factorial of 20
let result = 1n;
for (let i = 2n; i <= num; i++) {
result *= i;
}
document.getElementById("result").innerText = "Factorial of 20 is " + result;
}
document.addEventListener("DOMContentLoaded", function () {
calculateFactorial();
});
</script>
</body>
</html>
示例 4:BigInt Color Square
在这个例子中,利用 BigInt,我们在预定义的参数中生成随机颜色,并将它们应用于 colorSquare 进行演示。随机颜色的生成涉及乘法:通过 Math.random() 获得 0 和 1 之间的浮点数乘以最大颜色值。随后,我们通过 Math.floor() 将此结果向下舍入到最接近的整数,然后使用 BigInt() 将其转换为 BigInt。生成的 BigInt 是转换为十六进制字符串并返回的。
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
}
#colorSquare {
width: 400px;
height: 200px;
border: 2px solid #000;
}
</style>
</head>
<body>
<h2>BigInt Color Example</h2>
<div id="colorSquare"></div>
<script>
function generateRandomColor() {
const maxColorValue = 16777215n; // 0xFFFFFF in hexadecimal
const randomColor = BigInt(Math.floor(Math.random() * Number(maxColorValue)));
return `#${randomColor.toString(16).padStart(6, '0')}`;
}
const colorSquare = document.getElementById('colorSquare');
colorSquare.style.backgroundColor = generateRandomColor();
</script>
</body>
</html>
使用 BigInt 进行错误处理
此代码演示了使用常规数字添加 BigInt 的独特情况。在 JavaScript 中,我们需要执行到 BigInt 的显式转换。当我们尝试将 42(常规数)与 42n(或 BigInt)相加时,它抛出了一个错误,该错误在 try catch 的帮助下捕获并显示在屏幕上。
<!DOCTYPE html>
<html>
<body>
<h2>Adding BigInt & Regular Number</h2>
<div id="output"></div>
<script>
const regularNumber = 42;
const bigIntValue = BigInt(regularNumber); // Explicit conversion
document.getElementById("output").innerHTML =
`<p>Regular Number: ${regularNumber}</p>`+
`<p>BigInt Value: ${bigIntValue}</p>` +
`<p>Regular Number + BigInt Value results in:</p>`;
try {
const result = regularNumber + bigIntValue;
document.getElementById("output").innerHTML += `Result: ${result}`;
} catch (e) {
document.getElementById("output").innerHTML += `Error: ${e}`;
}
</script>
</body>
</html>