ES2020之BigInt

简介

  1. 这是一个新的数据类型
  2. 在ES中所有的Number类型都是使用64为浮点数来进行存储,因此Number的有效值表示的最大值就是2^53。而使用新的BigInt类型可以操作任意精度的整数

例子

使用

  1. 一般使用的时候可以在数字字面量后面加n
  2. 或者使用构造函数
const bigIntNum = 9999999999999999999999999999999999n
const bigIntNum2 = BigInt(9999999999999999999999999999999999)

console.log(bigIntNum,bigIntNum2); // 9999999999999999999999999999999999n 9999999999999999455752309870428160n
// 数据过大的时候,使用Bigint构造函数,我们应该用字符串表示

const bigIntNum3 = BigInt("9999999999999999999999999999999999")
console.log(bigIntNum3);

运算

同类型运算

支持+、-、*、/、**的操作

console.log(3n + 2n); // 5n
console.log(3n * 2n); // 6n
console.log(3n - 2n); // 1n
console.log(3n / 2n); // 1n
console.log(3n ** 2n); // 9n

我们会发现BigInt进行运算最终得到的都是整数,比如3n / 2n,最终得到的是1n,他支持的是向下取整

不同类型计算

字符串

字符串,他可以和字符串之间进行 + 号操作

console.log(2n + "hello"); // 2hello
console.log("world" + 3n); // world3
number
  1. BigInt不能和Number一起运算,会抛出类型错误
console.log(2 + 2n); // Cannot mix BigInt and other types, use explicit conversions
  1. 一些内置的数字处理的模块不支持对于BigInt处理
Math.pow(2n) // Cannot convert a BigInt value to a number
  1. BigInt与Number相等,但不是严格相等
console.log(2 == 2n); // true
console.log(2 === 2n); // false
  1. 可以比较大小
console.log(3n < 4); // true
console.log(4n > 3); // true
  1. 布尔值转化
console.log(!!0n); // false
console.log(!!1n); // true
  1. Number与BigInt转化,两者智能通过构造函数进行转换
console.log(Number(1n)); // 1
console.log(BigInt(1)); // 1n 

兼容性

BigInt数据类型只在一下浏览器支持

  1. Chrome 67+
  2. FIrefox 68+
  3. Safari 14+
  4. Node.js 12+

因为他是基本的数据类型,目前没有完整的兼容库来支持无法兼容的浏览器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值