在JavaScript中,Number
可以准确表达的最大数字是253,比253大的所有数字可以使用BigInt
表达。
BigInt(value);
value
注意, BigInt()
不是构造函数,因此不能使用 new
操作符。
可以这样定义一个 BigInt
变量:在一个整数字面量后面加 n
,如:10n
,或者调用函数BigInt()
。
const theBiggestInt = 9007199254740991n; const alsoHuge = BigInt(9007199254740991); // ↪ 9007199254740991n const hugeButString = BigInt('9007199254740991'); // ↪ 9007199254740991n
它在某些方面类似于 Number
,但是也有几个关键的不同点:不能和 Math
对象中的方法一起使用;不能和任何 Number
实例混合运算。
以下操作符可以和 BigInt
一起使用: +
、`*
`、`-
`、`**
`、`%
` 。
const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER); // ↪ 9007199254740991n const maxPlusOne = previousMaxSafe + 1n; // ↪ 9007199254740992n const theFuture = previousMaxSafe + 2n; // ↪ 9007199254740993n, this works now! const multi = previousMaxSafe * 2n; // ↪ 18014398509481982n const subtr = multi – 10n; // ↪ 18014398509481972n const mod = multi % 10n; // ↪ 2n const bigN = 2n ** 54n; // ↪ 18014398509481984n bigN * -1n // ↪ –18014398509481984n
/
操作符对于所有数字的运算也没问题。可是因为这些变量是 BigInt
而不是 BigDecimal
,该操作符会导致向零取整,也就是说不会返回小数部分。
当使用 BigInt
时,带小数的运算会被取整。
const expected = 4n / 2n; // ↪ 2n const rounded = 5n / 2n; // ↪ 2n, not 2.5n
BigInt
和 Number
不是严格相等的,但是宽松相等的。
0n === 0 // ↪ false 0n == 0 // ↪ true
Number
和 BigInt
可以像一般情况进行比较。
1n < 2 // ↪ true 2n > 1 // ↪ true 2 > 2 // ↪ false 2n > 2 // ↪ false 2n >= 2 // ↪ true
两者也可以混在一个数组内并排序。
const mixed = [4n, 6, -12n, 10, 4, 0, 0n]; // ↪ [4n, 6, -12n, 10, 4, 0, 0n] mixed.sort(); // ↪ [-12n, 0, 0n, 10, 4n, 4, 6]
BigInt
在转换成 Boolean
时和 Number
类似:通过 Boolean
函数;和 Logical Operators
||
, `&&
`, and !
一起使用;或者在像 if statement
这样的条件语句中。
if (0n) { console.log('Hello from the if!'); } else { console.log('Hello from the else!'); } // ↪ "Hello from the else!" 0n || 12n // ↪ 12n 0n && 12n // ↪ 0n Boolean(0n) // ↪ false Boolean(12n) // ↪ true !12n // ↪ false !0n // ↪ true
function isPrime(p) { for (let i = 2n; i * i <= p; i++) { if (p % i === 0n) return false; } return true; } // Takes a BigInt as an argument and returns a BigInt function nthPrime(nth) { let maybePrime = 2n; let prime = 0n; while (nth >= 0n) { if (isPrime(maybePrime)) { nth -= 1n; prime = maybePrime; } maybePrime += 1n; } return prime; } nthPrime(20n) // ↪ 73n