bigInt

186 阅读2分钟

baijiahao.baidu.com/s?id=168140…

BigInt是一种特殊的数字类型,它支持任意长度的整数。

要创建一个 bigint,可以在一个整数的末尾添加字符n,或者调用函数 BigInt()。BigInt 函数使用字符串、数字等来创建一个BigInt。

const bigint =1234567890123456789012345678901234567890n;const sameBigint = BigInt("1234567890123456789012345678901234567890");const bigintFromNumber =BigInt(10);// same as 10n

数学运算符

BigInt可以像常规数字一样使用,例如:

alert(1n+2n);// 3alert(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 bigintalert(bigint +BigInt(number));// 3// bigint to numberalert(Number(bigint)+ number);// 3

转换操作总是悄悄进行的,但是如果bigint太大,不适合数字类型,那么会进行截取操作,所以我们做这样的转换时应该特别小心。

bigint 不支持前置加号 +

加号运算符 +value 是将值转换为数字的一种众所周知的方法。

为了避免混淆,bigints不支持它:

let bigint =1n;alert(+bigint );// error

我们应该用Number()把一个bigint转换成数字。

比较

比较,例如<,>可以处理 bitint 和数字:

alert(2n>1n);// truealert(2n>1);// true

请注意,由于 number 和 bitint 属于不同的数据类型,它们可以相等==,但不能严格相等===:

alert(1==1n);// truealert(1===1n);// false

布尔运算

当在 if 或其他布尔运算中时,bigint 的行为类似于数字。

例如,在 if 中,bigint 0n为假,其他值为真:

if(0n){// never executes}

布尔运算符,如 ||、&&和其他运算符也适用于 biginit,其行为和 number 类似:

alert(1n||2);// 1 (1n is considered truthy)alert(0n||2);// 2 (0n is considered falsy)

兼容性

在如下浏览器和平台上支持:

Chrome 67+

FIrefox 68+

Safari 14+

Node.js 12+

由于它是基础的数据类型,目前没有完美的兼容库来支持那些不能原生支持的浏览器。