在 JavaScript 中,数字计算一直是一个非常重要的部分。但是由于 JavaScript 中数字的精度限制,经常会出现精度丢失的问题。为了解决这个问题,ES11 引入了 BigInt 类型,允许开发者使用无限制精度的数字。除此之外,ES11 还引入了一些新的 Date 对象方法,使得时间的处理更加方便。
BigInt 类型
BigInt 类型是一种新的 JavaScript 基本数据类型,用于表示任意精度的整数。BigInt 类型的值可以通过在整数后面加上 n 或者使用 BigInt() 函数来创建。
const bigInt1 = 9007199254740991n; const bigInt2 = BigInt(9007199254740991);
BigInt 类型的值可以与普通的数字进行运算,但是需要注意的是,BigInt 类型的值与普通的数字类型是不相等的。
const bigInt1 = 9007199254740991n; const number1 = 9007199254740991; console.log(bigInt1 == number1); // false console.log(bigInt1 === number1); // false
BigInt 类型的值也可以进行常见的运算操作,例如加减乘除、取模、幂等等。需要注意的是,在进行除法运算时,BigInt 类型的值只能得到整数结果。如果需要得到小数结果,需要将 BigInt 类型的值转换为普通的数字类型。
const bigInt1 = 9007199254740991n; const bigInt2 = 123456789012345678901234567890n; console.log(bigInt1 + bigInt2); // 123456789012345678910241766841981n console.log(bigInt2 - bigInt1); // 123456789012345678891465672839799n console.log(bigInt1 * bigInt2); // 111107927407868939928884800311772033590350365266747327290n console.log(bigInt2 / bigInt1); // 13717421072793n console.log(bigInt1 % bigInt2); // 9007199254740991n console.log(bigInt1 ** 2n); // 81129638414606663681390495662081n
Date 对象
Date 对象是 JavaScript 中表示日期和时间的对象。ES11 引入了一些新的 Date 对象方法,使得时间的处理更加方便。下面是一些常用的 Date 对象方法。
toLocaleString()
toLocaleString() 方法返回一个表示日期和时间的字符串,该字符串与当前执行环境的区域设置相关。
const date = new Date(); console.log(date.toLocaleString()); // 2022/2/28 下午10:05:13
toLocaleDateString()
toLocaleDateString() 方法返回一个表示日期的字符串,该字符串与当前执行环境的区域设置相关。
const date = new Date(); console.log(date.toLocaleDateString()); // 2022/2/28
toLocaleTimeString()
toLocaleTimeString() 方法返回一个表示时间的字符串,该字符串与当前执行环境的区域设置相关。
const date = new Date(); console.log(date.toLocaleTimeString()); // 下午10:05:13
getTimezoneOffset()
getTimezoneOffset() 方法返回当前时区与 UTC 时间之间的分钟差值。
const date = new Date(); console.log(date.getTimezoneOffset()); // -480
总结
ES11 中引入的 BigInt 类型和新的 Date 对象方法,使得 JavaScript 中数字的精度处理和时间的处理更加方便。开发者可以使用 BigInt 类型来处理需要无限制精度的数字,使用新的 Date 对象方法来处理时间。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/65de74461886fbafa4bbc7a0