【JavaScript_BigInt】BigInt的使用和注意事项

2022/7/17 1:17:43

本文主要是介绍【JavaScript_BigInt】BigInt的使用和注意事项,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

BigInt的定义

BigInt 是一种内置对象,它提供了一种方法来表示大于 2^53 - 1 的整数。这原本是 Javascript 中可以用 Number 表示的最大数字,也叫做最大安全整数。BigInt 可以表示任意大的整数。

安全整数的范围

超过这个范围,number类型的数字将会失去精度

Number.MAX_SAFE_INTEGER
// ↪ 99007199254740991    最大安全整数

Number.MIN_SAFE_INTEGER
// ↪ -99007199254740991   最小安全整数

如何使用BigInt

  1. 可以用在一个整数字面量后面加 n 的方式定义一个 BigInt ,如:10n,
  2. 或者调用构造函数 BigInt()(不能使用 new 运算符)并传递一个整数值或字符串值
const theBiggestInt = 9007199254740991n;

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

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

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

BigInt类型判断

typeof 123
// ↪ 'number'
typeof 123n
// ↪ 'bigint'
typeof BigInt(123)
// ↪ ''bigint'

BigInt运算

但是BigInt不支持单独使用运算符+,因为会默认为转换成Number,这是不允许的。

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

const expected = 4n / 2n;
// ↪ 2n

const rounded = 5n / 2n;
// ↪ 2n, not 2.5n

BigInt比较大小

// 不严格相等,严格不相等
0n === 0
// ↪ false

0n == 0
// ↪ true


// Number 和 BigInt 可以直接比较。
1n < 2
// ↪ true

2n > 1
// ↪ true

2 > 2
// ↪ false

2n > 2
// ↪ false

2n >= 2
// ↪ true

// BigInt可以和Number混入数组中进行排序
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无法使用JSON.stringify()方法

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

BigInt.prototype.toJSON = function() { return this.toString(); }
// 现在可以
JSON.stringify(BigInt(1));
// ↪ '"1"'

总结

  1. BigInt不能和Number类型数据混合运算,两者必须转换成同一种数据类型。BigInt和Number联众类型互相转换时,要注意可能会丢失精度
  2. BigInt和Numner可以直接作大小比较。
  3. BigInt可以和大部分运算符一起使用,除了单独使用+,因为会默认强制转化类型。
  4. BigInt作为条件判断转为Boolean时,和Number类型一致。
  5. 默认情况下BigInt无法在JSON中序列化
  6. bignumber.js 也是一种处理最大安全整数的方法
  7. BigInt不能调用Math中的方法


这篇关于【JavaScript_BigInt】BigInt的使用和注意事项的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程