<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          5 大 JavaScript ES12 特性,你現(xiàn)在可以開始使用的了

          共 7784字,需瀏覽 16分鐘

           ·

          2021-12-10 01:10

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

          翻譯 | 楊小愛


          ECMAScript 2021(第 12 版)現(xiàn)已可用,并附帶新功能和語法改進。ECMA International 已于 2021 年 6 月 22 日最終確定了這些規(guī)范。實施這些改進是為了使 JavaScript 更加健壯并幫助開發(fā)人員輕松完成任務(wù)。
          我將詳細展示 ECMAScript 2021 提供的前 5 項功能,以便您可以開始在您的項目中使用它們,并改善您的 JavaScript 體驗。初學(xué)者和有經(jīng)驗的開發(fā)人員可以從本文中受益。
          ECMAScript 2021 更新提供的 5 大 JavaScript 功能:
          • 數(shù)字分隔符

          • String.prototype.replaceAll

          • Promise.any() 和 AggregateError

          • 邏輯賦值運算符

          • 私有類方法和訪問器

          1、數(shù)字分隔符
          數(shù)字分隔符允許您在文字數(shù)字的數(shù)字之間添加下劃線,這使它們更具可讀性。當文件被解析時,這些下劃線將被自動去除。請參閱以下代碼片段以了解如何使用數(shù)字分隔符。
          // 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_200console.log(n2); // This will print: 1000000000.1502
          // Hexadecimal integer literal with digits grouped by byte.let n3 = 0x95_65_98_FA_A9console.log(n3); // This will print: 641654651561
          // BigInt literal with digits grouped by thousand.let n4 = 155_326_458_156_248_168_514nconsole.log(n4); // This will print: 155326458156248168514n

          2、String.prototype.replaceAll

          String 原型上的 replaceAll() 函數(shù)允許替換子字符串的所有實例,而無需使用正則表達式。如果在字符串上使用了 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() 將被觸發(fā)。

          另一方面, Promise.all() 將等到所有承諾都得到解決。以下是 any()、all() 和 allSettled() 的區(qū)別。

          any() — 如果至少有一個承諾被解決,這將執(zhí)行,如果所有承諾都被拒絕,則將拒絕。

          all() — 如果所有承諾都得到解決,這將執(zhí)行,如果至少一個承諾被拒絕,則將拒絕。

          allSettled() — 如果所有承諾都已解決或被拒絕,這將執(zhí)行。

          請參閱以下代碼片段以了解如何使用 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 賦值運算符 ||= 接受兩個操作數(shù),如果左操作數(shù)為假,則將右操作數(shù)分配給左操作數(shù)。請參閱以下代碼片段以了解如何使用邏輯 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 賦值運算符

          如果左操作數(shù)為真,邏輯 AND 賦值運算符 &&= 僅將右操作數(shù)分配給左操作數(shù)。請參閱以下代碼片段以了解如何使用邏輯 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、空合并賦值運算符

          如果左操作數(shù)為空或未定義,則空合并賦值運算符 ??= 僅將右操作數(shù)分配給左操作數(shù)。請參閱以下代碼片段以了解如何使用空合并賦值運算符。

          // 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、私有類方法和訪問器

          默認情況下,類方法和屬性是公共的,但可以使用哈希 # 前綴創(chuàng)建私有方法和屬性。ECMAScript 2021 更新已強制執(zhí)行隱私封裝。

          這些私有方法和屬性只能從類內(nèi)部訪問。請參閱以下代碼片段以了解如何使用私有方法。

          // 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.
          總結(jié)
          感謝您閱讀到此!
          以上內(nèi)容就是JavaScript ES12 (ECMAScript 2021) 更新提供的功能學(xué)習。現(xiàn)在,您可以繼續(xù)為您當前或即將開展的項目實施上述功能。
          如果您覺得對您有幫助,也請您分享給您身邊的朋友,也許對他也會有所幫助。


          學(xué)習更多技能

          請點擊下方公眾號

          瀏覽 33
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产精品99 | 色色色色色色色色色五月婷婷 | 中国黄色A片 | 大鸡巴操骚逼视频 | 国产av.www |