【ES11(2020)】新增数据类型 BigInt

在 ES10 增加了新的原始数据类型:BigInt,表示一个任意精度的整数,可以表示超长数据,可以超出2的53次方。

Js 中 Number类型只能安全的表示-(2^53-1) 至 2^53-1范的值。

可以用在一个整数字面量后面加 n的方式定义一个 BigInt ,如:10n,或者调用函数BigInt()

const theBiggestInt = 9007199254740991n;

const alsoHuge = BigInt(9007199254740991);
// 9007199254740991n

const hugeString = BigInt("9007199254740991");
// 9007199254740991n

const hugeHex = BigInt("0x1fffffffffffff");
// 9007199254740991n

const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
// 9007199254740991n

它在某些方面类似于 Number ,但是也有几个关键的不同点:

  • 不能用于 Math 对象中的方法;
  • 不能和任何 Number实例混合运算,两者必须转换成同一种类型。在两种类型来回转换时要小心,因为 BigInt 变量在转换成 Number 变量时可能会丢失精度。
typeof 1n === 'bigint'; // true
typeof BigInt('1') === 'bigint'; // true

// 使用 Object 包装后, BigInt 被认为是一个普通 "object" :
typeof Object(1n) === 'object'; // true

运算

以下操作符可以和BigInt 一起使用:
+、*、-、**、%

>>>(无符号右移)之外的 位操作 也可以支持。因为 BigInt 都是有符号的, >>> (无符号右移)不能用于 BigInt。
为了兼容 asm.jsBigInt 不支持单目 (+) 运算符。

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    不是2.5n

BigInt 和 Number 比较

BigIntNumber 不是严格相等的,但是宽松相等的。

0n === 0
//  false

0n == 0
//  true

NumberBigInt 可以进行比较

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.asIntN() 将 BigInt 值转换为一个 -2width-1 与 2width-1-1 之间的有符号整数。

BigInt.asUintN() 将一个 BigInt 值转换为 0 与 2width-1 之间的无符号整数。

实例方法
BigInt.prototype.toLocaleString() 返回此数字的 language-sensitive 形式的字符串。覆盖 Object.prototype.toLocaleString() 方法。

BigInt.prototype.toString() 返回以指定基数(base)表示指定数字的字符串。覆盖 Object.prototype.toString() 方法。

BigInt.prototype.valueOf() 返回指定对象的基元值。 覆盖 Object.prototype.valueOf() 方法。

JSON中使用

对任何 BigInt 值使用JSON.stringify()都会引发TypeError,因为默认情况下 BigInt 值不会在 JSON 中序列化。但是,如果需要,可以实现 toJSON方法:

BigInt.prototype.toJSON = function() { 
	return this.toString(); 
}

JSON.stringify(BigInt(1));
//  "1"
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

优小U

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值