如果可以实现记得点赞分享,谢谢老铁~
最新的ES2020定义了九种数据类型。六种数据类型是原语,由 typeof 运算符、null、Object 和 Function 检查。基元是未定义的、布尔型、数字、字符串、符号,新的基元是 BigInt。在 JavaScript 中,我们第一次可以存储大于 Number 的数字,换句话说,存储大于 2 53 - 1 的整数。
我们可以通过在整数末尾附加**n或使用构造函数****BigInt()**来创建 BigInt
const big = 12345n;
typeof big; // "bigint"
const sameBig = BigInt("12345"); //12345n
const oneMoreSame = BigInt(12345); //12345n
使用 BigInt 进行操作
像+、*、-、**、% 这样的操作可以像数字一样使用。
const huge = 20n + 4n; //24n
const oneMore = 20n - 4n; //16n
const oneBig = 20n ** 4n; //160000n
还可以使用按位运算符,但 >>>(零填充右移)除外,因为所有 BigInt 都已签名。
const big = 20n & 4n; //4n
我们需要记住,/ 运算的结果将像任何其他数字一样向 0 舍入。
const big = 20n / 4n; //5n
const huge = 20n / 3n; //6n
不支持一元 +。
const big = +3n; //Error: Cannot convert a BigInt value to a number
与其他类型的比较和运算
您不能将 BigInt 与其他类型混合使用,甚至不能与 Number 混合使用。像这样的事情会给你一个错误。
const big = 20n + 4; //Error: Cannot mix BigInt and other types
但我们可以转换它们。
const big = 20n + BigInt(4); //24n
const huge = Number(20n) + 4; //24
使用字符串,可以连接 BigInt。
const big = 20n + "4"; //"204"
BigInt 松散地等于 Number,但并不严格相等。
20n == 20; //true
20n === 20; //false
Number 和 BigInt 数据类型可以自然地进行比较。
20 > 10n; //true
20n >= 20; // true
我们可以看到 Number 和 BigInt 之间的相似之处,但重要的一点是它不能与内置 Math 对象中的方法一起使用。另一方面,当 BigInt 与逻辑运算符(||、&&、!)一起使用、转换为布尔值并在条件测试中使用时,其行为类似于 Number。
const big = Boolean(20n); //true
!big; //false