专业编程基础技术教程

网站首页 > 基础教程 正文

JS基本数据类型BigInt

ccvgpt 2024-12-14 10:19:56 基础教程 1 ℃

在 JavaScript 中,有一个特殊的数据类型BigInt,它可以存储非常大的整数,甚至可以存储超过 2 的 32 次方的所有整数。

BigInt是一种无符号整数类型,它可以表示任何正整数,包括无限大和无限小。JavaScript 中的BigInt使用二进制表示法,因此它的值是无限的,并且永远不会溢出或产生舍入误差。

JS基本数据类型BigInt

要创建BigInt对象,可以使用Number.bigInt方法。例如,以下代码将创建一个非常大的整数:

let bigInt = Number.bigInt(2**32 + 1);  

在这个例子中,2**32 + 1是一个非常大的整数,它可以使用 32 位二进制表示。Number.bigInt方法将返回一个BigInt对象,可以表示这个非常大的整数。

如何创建 BigInt ?

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

const theBiggestInt = 9007199254740991n;
const alsoHuge = BigInt(9007199254740991);
console.log(theBiggestInt, alsoHuge);
// 9007199254740991n 9007199254740991n

安全整数的范围

超过这个范围,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"'

需要注意的是,BigInt对象是不可变的,也就是说,一旦创建,就无法更改其值。如果需要更改BigInt对象的值,必须创建一个新的BigInt对象。

BigInt对象在 JavaScript 中主要用于处理非常大的整数,例如在密码学和安全方面。

总结

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

最近发表
标签列表