0
点赞
收藏
分享

微信扫一扫

5 大 JavaScript ES12 特性,你现在可以开始使用的了

5 大 JavaScript ES12 特性,你现在可以开始使用的了_代码片段

英文 | https://levelup.gitconnected.com/top-5-javascript-es12-features-you-should-start-using-now-b16a8b5353b1

翻译 | 杨小爱


ECMAScript 2021(第 12 版)现已可用,并附带新功能和语法改进。ECMA International 已于 2021 年 6 月 22 日最终确定了这些规范。实施这些改进是为了使 JavaScript 更加健壮并帮助开发人员轻松完成任务。

我将详细展示 ECMAScript 2021 提供的前 5 项功能,以便您可以开始在您的项目中使用它们,并改善您的 JavaScript 体验。初学者和有经验的开发人员可以从本文中受益。

ECMAScript 2021 更新提供的 5 大 JavaScript 功能:

  • 数字分隔符
  • String.prototype.replaceAll
  • Promise.any() 和 AggregateError
  • 逻辑赋值运算符
  • 私有类方法和访问器

1、数字分隔符

数字分隔符允许您在文字数字的数字之间添加下划线,这使它们更具可读性。当文件被解析时,这些下划线将被自动去除。请参阅以下代码片段以了解如何使用数字分隔符。

// 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

私有访问器是——私有的 Getter 和 Setter。Getter 允许您获取类属性的值,而 Setter 允许您为类属性分配值。您可以使用哈希 # 前缀定义私有 getter。

get #newAccountPassword() {}

同样,您可以使用哈希 # 前缀定义私有 setter。

set #generateAccountPassword(newPassword) {}

请参阅以下代码片段以了解如何使用私有 Getter 和 Setter。

// Let's create a class named Str.
class Str {
// The private attributes can be created by prepending '#'
// before the attribute name.
#uniqueStr;


constructor() {}


// A private Setters can be created by prepending '#' before
// the Setter name.
set #generateUniqueStringByCustomLength(length = 24) {
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let randomStr = "";


for (let i = 0; i < length; i++) {
const randomNum = Math.floor(Math.random() * characters.length);
randomStr += characters[randomNum];
}


this.#uniqueStr = randomStr;
}


// Public Setter
set setRandomString(length) {
this.#generateUniqueStringByCustomLength = length;
}


// A private getter can be created by prepending '#' before
// the Getter name.
get #fetchUniqueString() {
return this.#uniqueStr;
}


// Public Getter
get getRandomString() {
return this.#fetchUniqueString;
}
}


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.

总结

感谢您阅读到此!

以上内容就是JavaScript ES12 (ECMAScript 2021) 更新提供的功能学习。现在,您可以继续为您当前或即将开展的项目实施上述功能。

如果您觉得对您有帮助,也请您分享给您身边的朋友,也许对他也会有所帮助。


学习更多技能

请点击下方公众号



5 大 JavaScript ES12 特性,你现在可以开始使用的了_操作数_02

5 大 JavaScript ES12 特性,你现在可以开始使用的了_操作数_03

举报

相关推荐

0 条评论