ES11新增了一个数据类型——BigInt,用于表示大于2的53次方的整数。在JavaScript中,Number类型最大可以表示2的53次方的整数,因此当要处理非常大的整数时,Number类型就会出现精度丢失的问题。BigInt数据类型可以解决该问题,同时也可以支持更大的整数运算。
BigInt数据类型的定义
BigInt数据类型即大整数,用于表示超出Number表示范围内的整数。BigInt需要以n结尾的方式来定义一个数字,例如:10n、100n、10000n。也可以使用BigInt()构造函数生成BigInt类型的值,如下所示:
const bigNum = BigInt(1234567891011121314151617); console.log(bigNum); // 1234567891011121314151617n
BigInt数据类型的运算
与Number类型一样,BigInt数据类型也可以进行基本的数学运算,例如加减乘除、取模和位运算。BigInt使用与Number相同的运算符,只不过需要在最后加上n。例如,以下是BigInt的加法运算:
const x = 123456789987654321n; const y = 987654321123456789n; const result = x + y; console.log(result); // 1111111111111111110n
BigInt也可以和Number类型进行运算,例如:
const bigNum = 123456789987654321n; const smallNum = 500; const result1 = bigNum + BigInt(smallNum); const result2 = bigNum * smallNum; console.log(result1); // 123456789987654821n console.log(result2); // 61728394993827160500n
需要注意的是,在使用BigInt和Number类型进行运算时,需要显示地使用BigInt()来将Number类型转换为BigInt类型。
BigInt数据类型的比较
与Number不同,BigInt的比较不支持简单的比较运算符,如<、>、<=或>=。相反,BigInt提供了三个方法来比较BigInt的值:BigInt.prototype.valueOf()
、BigInt.prototype.toString()
和Object.is()
。
const bigInt1 = BigInt('123456789'); const bigInt2 = BigInt('987654321'); console.log(bigInt1.valueOf() < bigInt2.valueOf()); // true console.log(bigint1.toString() < bigint2.toString()); // true console.log(Object.is(bigInt1, bigInt2)); // false
BigInt数据类型的类型判断
在JavaScript中,我们可以使用typeof运算符来判断数据类型。但是在BigInt类型上,typeof返回的是object。为了检查值是否是BigInt类型,我们可以使用typeof x === 'bigint'
来检查。
const bigInt = 789456123123456789n; console.log(typeof bigInt); // "bigint" console.log(typeof bigInt === 'bigint'); // true
总结
BigInt数据类型的出现为大整数计算提供了便利,解决了Number类型的精度丢失和运算范围问题。BigInt类型与Number类型使用相似的运算符和建议的语法,可以快速上手,提高数据处理效率。最后需要注意的是,因为BigInt类型是ES11中新增的特性,因此在低版本的JavaScript中不被支持。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/64a6be9f48841e98943626a3