目录
验证例子1: n1为bigint, n2为数字, 使用Math.pow()函数来求两者的平方
概述
BigInt是javascript中的内置对象, 一般用来表示大数 (大于2^53 - 1的整数), 当遇到大数操作时应该想到BigInt, 他和number具有相似的行为, 同样可以用来加减乘除比较等等
场景
数字的最大安全值 : Number.MAX_SAFE_INTEGER 也就是 2^53 - 1
我们来看看操作数字的最大安全值会发生什么 ?
const n1 = Number.MAX_SAFE_INTEGER * 10;
console.log(Number.MAX_SAFE_INTEGER, n1);
可以看到 原本最大安全值*10的结果应该是 90071992547409910 但结果不一样, 说明number的大数的操作并不安全, 接下来看看BigInt
定义BigInt
想要定义一个大数, 你可以在数字或者字符串后加个n, 或者使用BigInt() , typeof 检测大数的类型是 bigint
例子
const n1 = Number.MAX_SAFE_INTEGER;
const n2 = 10n
const res = BigInt(n1) * BigInt(10);
console.log(n1, res)
console.log(typeof n2, typeof res);
可以看到使用bigint来进行计算结果就是正确的
使用BigInt时的注意点
使用大数时需要注意:
- BigInt类型不能和内置函数Math共同使用
- BigInt不能和number类型进行运算, 只能和同为BigInt的数字进行运算
- BigInt可以和number进行比较
- BigInt不能转小数, 只能转整数, 遇到不是数字的情况(布尔值或者[] )内部应该会尝试先将其转为数字
验证例子1: n1为bigint, n2为数字, 使用Math.pow()函数来求两者的平方
const n1 = 10n;
try {
console.log(Math.pow(n1, 2));
} catch (error) {
console.log(error);
}
const n2 = 10;
console.log(Math.pow(n2, 2));
可以看到确实大数不能和math相关函数配合使用
验证例子2: 使用大数和number进行运算和比较
const n1 = 10n;
const n2 = 20;
try {
console.log(n1 + n2);
} catch (error) {
console.log(error);
}
console.log(n1 + BigInt(n2));
console.log(n1 > n2);
结果大数不能和number进行运算, 可以和number进行比较
验证例子3: BigInt不能转小数
try {
console.log(BigInt(22.22));
} catch (error) {
console.log(error);
}
报错内容大概是不能转换成bigint因为他不是个整数
BigInt的内部转换
console.log(BigInt(true));
console.log(BigInt(false));
console.log(BigInt([]));
console.log(BigInt("1"));
可以看到确实转换成功了, 此时你可能会认为内部可能做了+单目运算符或者Number()的运算, 但是结果是令人遗憾的
try {
console.log(BigInt(null));
} catch (error) {
console.log(error);
}
具体转换也不必太过深究...实际也用不到
BigInt运算结果为小数会取整
BigInt的实例方法
- toLocaleString 返回此数字的 language-sensitive 形式的字符串
- toString 返回以指定基数(base)表示指定数字的字符串
- valueOf 返回指定对象的基元值
console.log(2n.toLocaleString());
console.log(2n.toString(2));
console.log(2n.valueOf());
可以看到 toString 确实能转成2进制, 其他两个概念大家可以自己查查