BigInt: JavaScript 中任意精度的整数
BigInt
是 JavaScript 中的一种新型数字原始值,可以表示任意精度的整数。通过 BigInt
,您可以安全地存储并操作即使超出 Number
安全整数限制的大整数。本文通过对比 JavaScript 中的 BigInt
和 Number
,逐步介绍它的一些使用场景,并说明 Chrome 67 中的新功能。
BigInt
是 JavaScript 中的一种新型数字原始值,可以表示任意精度的整数。通过 BigInt
,您可以安全地存储并操作即使超出 Number
安全整数限制的大整数。本文通过对比 JavaScript 中的 BigInt
和 Number
,逐步介绍它的一些使用场景,并说明 Chrome 67 中的新功能。
ES2019 引入了 String.prototype.trimStart()
和 String.prototype.trimEnd()
:
const string = ' hello world ';
string.trimStart();
// → 'hello world '
string.trimEnd();
// → ' hello world'
string.trim(); // ES5
// → 'hello world'
此功能之前通过非标准的 trimLeft()
和 trimRight()
方法可以使用,这些方法作为新方法的别名保留,以确保向后兼容。
const string = ' hello world ';
string.trimStart();
// → 'hello world '
string.trimLeft();
// → 'hello world '
string.trimEnd();
// → ' hello world'
string.trimRight();
// → ' hello world'
string.trim(); // ES5
// → 'hello world'
Function.prototype.toString()
现在会返回源码文本的精确部分,包括空格和注释。以下是旧行为与新行为的对比示例:
动态 import()
引入了一种类似函数的新形式的 import
,相比静态 import
解锁了新的功能。这篇文章对比了两者并概述了新功能。
Promise.prototype.finally
使得可以注册在 Promise 被解决(即成功或拒绝)时调用的回调函数。
想象一下,你想要获取一些数据并显示在页面上。哦,你希望请求开始时显示一个加载动画,并且在请求完成后隐藏它。当出现问题时,你会显示一条错误消息。
const fetchAndDisplay = ({ url, element }) => {
showLoadingSpinner();
fetch(url)
.then((response) => response.text())
.then((text) => {
element.textContent = text;
hideLoadingSpinner();
})
.catch((error) => {
element.textContent = error.message;
hideLoadingSpinner();
});
};
国际化是一件难事。处理复数是一个可能看起来很简单的问题,直到你发现每种语言都有自己的复数规则。
对于英语的复数化规则,只有两种可能的结果。让我们以“cat(猫)”这个词为例:
'one'
形式,在英语中称为单数。'other'
形式(唯一的其它形式),在英语中称为复数。全新的 Intl.PluralRules
API 可以告诉你,在给定语言中哪种形式适用于特定数字。
const pr = new Intl.PluralRules('en-US');
pr.select(0); // 'other' (例如 '0 cats')
pr.select(0.5); // 'other' (例如 '0.5 cats')
pr.select(1); // 'one' (例如 '1 cat')
pr.select(1.5); // 'other' (例如 '1.5 cats')
pr.select(2); // 'other' (例如 '2 cats')
在讨论_对象的剩余和扩展属性_之前,让我们回忆一下一个非常相似的功能。
经典的 ECMAScript 2015 引入了用于数组解构赋值的_剩余元素_和数组字面量的_扩展元素_。
// 数组解构赋值的剩余元素:
const primes = [2, 3, 5, 7, 11];
const [first, second, ...rest] = primes;
console.log(first); // 2
console.log(second); // 3
console.log(rest); // [5, 7, 11]
// 数组字面量的扩展元素:
const primesCopy = [first, second, ...rest];
console.log(primesCopy); // [2, 3, 5, 7, 11]
那么有哪些新特性呢?一个提案使对象字面量也支持剩余和扩展属性。
// 对象解构赋值的剩余属性:
const person = {
firstName: 'Sebastian',
lastName: 'Markbåge',
country: 'USA',
state: 'CA',
};
const { firstName, lastName, ...rest } = person;
console.log(firstName); // Sebastian
console.log(lastName); // Markbåge
console.log(rest); // { country: 'USA', state: 'CA' }