BigInt是一种特殊的数字类型,它支持任意长度的整数。
创建bigint的方法是在整型文字的末尾加上n,或者调用函数bigint从字符串、数字等创建bigint。
const bigint = 1234567890123456789012345678901234567890n; const sameBigint = BigInt("1234567890123456789012345678901234567890"); const bigintFromNumber = BigInt(10); // same as 10n数学运算符
BigInt通常可以像普通数字一样使用,例如:
alert(1n + 2n); // 3 alert(5n / 2n); // 2
请注意:除法5/2返回的是四舍五入的结果,没有小数部分。所有对bigint类型的操作都返回bigint类型。
我们不能把bigint和普通数字混在一起:
alert(1n + 2); // Error: Cannot mix BigInt and other types
如果需要,应该显式地转换它们:使用BigInt()或Number(),像这样:
let bigint = 1n; let number = 2; // number to bigint alert(bigint + BigInt(number)); // 3 // bigint to number alert(Number(bigint) + number); // 3
转换操作总是静默的,从不出错,但是如果bigint太大,不适合数字类型,那么额外的位将被切断,所以我们在进行这种转换时应该小心。
一元加操作符+值是一种常用的将值转换为数字的方法。
为了避免混淆,bigint不支持:
let bigint = 1n; alert( +bigint ); // error比较
比较,例如<,>可以很好地用于bigint和数字:
alert( 2n > 1n ); // true alert( 2n > 1 ); // true
但是请注意,由于数字和bigint属于不同的类型,它们可以等于==,但不能严格等于===:
alert( 1 == 1n ); // true alert( 1 === 1n ); // false布尔操作
在if或其他布尔操作中,bigint的行为与数字类似。
例如,在if中,bigint 0n为假值,其他值为真值:
if (0n) { // never executes } alert( 1n || 2 ); // 1 (1n is considered truthy) alert( 0n || 2 ); // 2 (0n is considered falsy)