The new primitive data type BigInt
Background of BigInt Introduction in ECMAScript 11
JavaScript's Number type is based on the IEEE 754 double-precision floating-point standard, which can safely represent integers up to 2^53 - 1 (i.e., Number.MAX_SAFE_INTEGER
). Beyond this range, calculation results may lose precision. The introduction of the BigInt type solves this problem by allowing the representation and manipulation of integers with arbitrary precision.
Basic Characteristics of BigInt
BigInt is a new primitive data type used to represent integers larger than 2^53 - 1. Its main differences from the Number type include:
- Literals end with
n
, e.g.,123n
- Cannot be mixed with Number types in operations
- Does not support methods from the
Math
object - Behaves the same as Number when converted to a boolean
const bigInt = 9007199254740993n;
console.log(typeof bigInt); // "bigint"
Ways to Create BigInt
There are three main ways to create a BigInt:
- Append
n
directly to a number - Use the
BigInt()
constructor - Use the
BigInt.asIntN()
andBigInt.asUintN()
methods
// Method 1: Literal
const a = 123456789012345678901234567890n;
// Method 2: Constructor
const b = BigInt("12345678901234567890");
// Method 3: Bit-limited conversion
const c = BigInt.asIntN(64, 12345678901234567890n);
BigInt Operations
BigInt supports most arithmetic operators but cannot be mixed with Number types in operations:
const x = 10n;
const y = 20n;
console.log(x + y); // 30n
console.log(x * y); // 200n
console.log(y / x); // 2n (Note: BigInt division truncates the fractional part)
console.log(y % x); // 0n
// Error example
try {
console.log(x + 10); // Throws TypeError
} catch (e) {
console.error(e.message); // "Cannot mix BigInt and other types"
}
BigInt Comparison Operations
BigInt can be compared with Number, but type conversion must be considered:
console.log(10n == 10); // true
console.log(10n === 10); // false
console.log(10n > 5); // true
console.log(10n < 20); // true
BigInt Bitwise Operations
BigInt supports all bitwise operations, including:
const a = 0b1100n;
const b = 0b1010n;
console.log(a & b); // 0b1000n (8n)
console.log(a | b); // 0b1110n (14n)
console.log(a ^ b); // 0b0110n (6n)
console.log(~a); // -13n (bitwise NOT)
BigInt Type Conversion
BigInt can be converted to other types, but precision issues must be considered:
// Convert to boolean
console.log(Boolean(0n)); // false
console.log(Boolean(1n)); // true
// Convert to string
console.log(100n.toString()); // "100"
console.log(String(100n)); // "100"
// Convert to Number (may lose precision)
console.log(Number(9007199254740993n)); // 9007199254740992
Practical BigInt Methods
ECMAScript provides several practical BigInt methods:
// Check if it's a BigInt
console.log(typeof 100n === "bigint"); // true
// Bit limitation
const bigNum = 12345678901234567890n;
console.log(BigInt.asIntN(32, bigNum)); // -350287150n
console.log(BigInt.asUintN(32, bigNum)); // 3944680146n
BigInt Use Cases
BigInt is particularly suitable for the following scenarios:
- High-precision mathematical calculations
- Large integer ID handling
- Cryptographic algorithm implementation
- Financial calculations
// Large integer ID handling
const userId = 9007199254740993n;
console.log(`User ID: ${userId}`);
// Fibonacci sequence calculation (large number version)
function fibonacci(n) {
let a = 0n, b = 1n;
for (let i = 0n; i < n; i++) {
[a, b] = [b, a + b];
}
return a;
}
console.log(fibonacci(100n)); // 354224848179261915075n
BigInt Considerations
When using BigInt, keep the following points in mind:
- JSON serialization issues
- Browser compatibility
- Performance considerations
- Interaction with third-party libraries
// JSON serialization issue
const obj = { id: 123n };
try {
JSON.stringify(obj); // Throws TypeError
} catch (e) {
console.error(e.message); // "Do not know how to serialize a BigInt"
}
// Solution: Custom serialization
const replacer = (key, value) =>
typeof value === "bigint" ? value.toString() : value;
console.log(JSON.stringify(obj, replacer)); // {"id":"123"}
BigInt Performance Considerations
Although BigInt provides high-precision calculation capabilities, its performance is generally slower than the Number type:
// Performance test
const testCount = 1000000;
console.time("Number addition");
let numSum = 0;
for (let i = 0; i < testCount; i++) {
numSum += i;
}
console.timeEnd("Number addition");
console.time("BigInt addition");
let bigSum = 0n;
for (let i = 0n; i < BigInt(testCount); i++) {
bigSum += i;
}
console.timeEnd("BigInt addition");
BigInt Browser Compatibility
As of now, all modern browsers support BigInt, but older browsers may require a polyfill:
// Check if the browser supports BigInt
if (typeof BigInt === "undefined") {
console.log("BigInt is not supported in the current environment");
// A third-party polyfill can be used
} else {
console.log("BigInt is supported in the current environment");
}
BigInt and TypeScript
To use BigInt in TypeScript, set target
to es2020
or higher in the configuration:
// tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020"]
}
}
// Usage example
const bigInt: bigint = 123n;
console.log(bigInt * 2n);
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn