5 大 JavaScript ES12 特性,你现在可以开始使用的了
英文 | https://levelup.gitconnected.com/top-5-javascript-es12-features-you-should-start-using-now-b16a8b5353b1
翻译 | 杨小爱
数字分隔符
String.prototype.replaceAll
Promise.any() 和 AggregateError
逻辑赋值运算符
私有类方法和访问器
// Decimal integer literal with digits grouped by thousand.
let n1 = 1_000_000_000;
console.log(n1); // This will print: 1000000000
// Decimal literal with digits grouped by thousand.
let n2 = 1_000_000_000.150_200
console.log(n2); // This will print: 1000000000.1502
// Hexadecimal integer literal with digits grouped by byte.
let n3 = 0x95_65_98_FA_A9
console.log(n3); // This will print: 641654651561
// BigInt literal with digits grouped by thousand.
let n4 = 155_326_458_156_248_168_514n
console.log(n4); // This will print: 155326458156248168514n
2、String.prototype.replaceAll
String 原型上的 replaceAll() 函数允许替换子字符串的所有实例,而无需使用正则表达式。如果在字符串上使用了 thereplace(),它只会替换该值的第一个实例。
另一方面,replaceAll() 提供替换该值的所有实例的功能。请参阅以下代码片段以了解如何使用 replaceAll()。
// Declare a variable and store some value.
const orgStr = 'JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled and multi-paradigm.';
// To replace single instance, use replace().
let newStr = orgStr.replace('JavaScript', 'TypeScript');
console.log(newStr);
// To replace all instances, use replaceAll().
let newStr2 = orgStr.replaceAll('JavaScript', 'TypeScript');
console.log(newStr2);
3、Promise.any() 和 AggregateError
Promise.any 与 Promise.all() 正好相反。如果任何承诺得到解决, Promise.any() 将被触发。
另一方面, Promise.all() 将等到所有承诺都得到解决。以下是 any()、all() 和 allSettled() 的区别。
any() — 如果至少有一个承诺被解决,这将执行,如果所有承诺都被拒绝,则将拒绝。
all() — 如果所有承诺都得到解决,这将执行,如果至少一个承诺被拒绝,则将拒绝。
allSettled() — 如果所有承诺都已解决或被拒绝,这将执行。
请参阅以下代码片段以了解如何使用 Promise.any()。
// Create a Promise.
const promise1 = new Promise((resolve, reject) => {
// After 2 seconds resolve the first promise.
setTimeout(() => resolve("The first promise has been resolved."), 2000);
});
// Create a Promise.
const promise2 = new Promise((resolve, reject) => {
// After 1 second resolve the second promise.
setTimeout(() => resolve("The second promise has been resolved."), 1000);
});
// Create a Promise.
const promise3 = new Promise((resolve, reject) => {
// After 3 seconds resolve the third promise.
setTimeout(() => resolve("The third promise has been resolved."), 3000);
});
(async function () {
const data = await Promise.any([promise1, promise2, promise3]);
// Print the data returned from the first resolved Promise.
console.log(data);
// The above will print: The second promise has been resolved.
})();
如果所有 Promise 都被拒绝,则会抛出 AggregateError 异常。请参阅以下代码片段以了解如何处理异常。
// Create a Promise.
const promise1 = new Promise((resolve, reject) => {
// After 1 second reject the first promise.
setTimeout(() => reject("The first promise has been rejected."), 1000);
});
// Create a Promise.
const promise2 = new Promise((resolve, reject) => {
// After 500 miliseconds reject the second promise.
setTimeout(() => reject("The second promise has been rejected."), 500);
});
// Try executing the Promises.
(async function () {
try {
const data = await Promise.any([promise1, promise2]);
console.log(data);
} catch (error) {
// If all Promises gets rejected, then this try-catch block will handle
// the aggregate errors.
console.log("Error: ", error);
}
})();
4、逻辑赋值运算符
ECMAScript 2021 更新中引入了三个逻辑赋值运算符。这些提供了逻辑运算符和赋值表达式的组合。
逻辑 OR 赋值运算符 ||=
逻辑与赋值运算符 &&=
空合并赋值运算符 ??=
4.1、 逻辑 OR 赋值运算符
逻辑 OR 赋值运算符 ||= 接受两个操作数,如果左操作数为假,则将右操作数分配给左操作数。请参阅以下代码片段以了解如何使用逻辑 OR 赋值运算符。
// In the example, the ||= will check if the songsCount is false (0).
// If false, then the right value will be assigned to the left variable.
let myPlaylist = {songsCount: 0, songs:[]};
myPlaylist.songsCount ||= 100;
console.log(myPlaylist); // This will print: {songsCount: 100, songs: Array(0)}
逻辑 OR 赋值运算符短路。此运算符 ||= 等效于以下使用逻辑 OR 运算符的语句。
a || (a = b)
4.2、逻辑 AND 赋值运算符
如果左操作数为真,逻辑 AND 赋值运算符 &&= 仅将右操作数分配给左操作数。请参阅以下代码片段以了解如何使用逻辑 AND 赋值运算符。
// In the example, the &&= will check if the filesCount is true.
// If true, then the right value will be assigned to the left variable.
let myFiles = {filesCount: 100, files:[]};
myFiles.filesCount &&= 5;
console.log(myFiles); // This will print: {filesCount: 5, files: Array(0)}
逻辑 AND 赋值运算符也会短路。此运算符 &&= 等效于以下使用逻辑 AND 运算符的语句。
a && (a = b)
4.3、空合并赋值运算符
如果左操作数为空或未定义,则空合并赋值运算符 ??= 仅将右操作数分配给左操作数。请参阅以下代码片段以了解如何使用空合并赋值运算符。
// In the example, the ??= will check if the lastname is null or undefined.
// If null or undefined, then the right value will be assigned to the left variable.
let userDetails = {firstname: 'Katina', age: 24}
userDetails.lastname ??= 'Dawson';
console.log(userDetails); // This will print: {firstname: 'Katina', age: 24, lastname: 'Dawson'}
空合并赋值运算符也会短路。此运算符 ??= 等效于以下使用空值合并运算符的语句。
a ?? (a = b)
5、私有类方法和访问器
默认情况下,类方法和属性是公共的,但可以使用哈希 # 前缀创建私有方法和属性。ECMAScript 2021 更新已强制执行隐私封装。
这些私有方法和属性只能从类内部访问。请参阅以下代码片段以了解如何使用私有方法。
// Let's create a class named User.
class User {
constructor() {}
// The private methods can be created by prepending '#' before
// the method name.
#generateAPIKey() {
return "d8cf946093107898cb64963ab34be6b7e22662179a8ea48ca5603f8216748767";
}
getAPIKey() {
// The private methods can be accessed by using '#' before
// the method name.
return this.#generateAPIKey();
}
}
const user = new User();
const userAPIKey = user.getAPIKey();
console.log(userAPIKey); // This will print: d8cf946093107898cb64963ab34be6b7e22662179a8ea48ca5603f8216748767
get
set #generateAccountPassword(newPassword) {}
// Let's create a class named Str.
class Str {
// The private attributes can be created by prepending '#'
// before the attribute name.
constructor() {}
// A private Setters can be created by prepending '#' before
// the Setter name.
set
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let randomStr = "";
for (let i = 0; i < length; i++) {
const randomNum = Math.floor(Math.random() * characters.length);
randomStr += characters[randomNum];
}
this.
}
// Public Setter
set setRandomString(length) {
this.
}
// A private getter can be created by prepending '#' before
// the Getter name.
get
return this.
}
// Public Getter
get getRandomString() {
return this.
}
}
const str = new Str();
// Calling a public Setter which will then access the private Setter
// within the class.
str.setRandomString = 20;
// Calling a public Getter which will then access the private Getter
// withing the class.
const uniqueStr = str.getRandomString;
console.log(uniqueStr); // This will print a random string everytime you execute the Getter after the Setter.
学习更多技能
请点击下方公众号