# JavaScript 2021(ES12) New Features ## Numeric separators (數值分隔符) (IE&Opera Mobile不支援) 增加數字閱讀性 To improve readability for numeric literals. ```javascript= const amount = 1_000_000_000; //1000000000 const amount = 1_475_938.38; //1475938.38 ``` ## String.protype.replaceAll (IE不支援) ```javascript= //Before const str = "I like my dog, my dog loves me"; const newStr = str.replace("dog", "cat"); console.log(newStr); //I like my cat, my dog loves me const newStr2 = str.replaceAll("dog", "cat"); //I like my cat, my cat loves me console.log(newStr2); const regex = /Dog/ig; console.log(str.replaceAll(regex, 'fish')); //I like my fish, my fish loves me ``` 注意:當使用regular expression一定要包含 global flag /g 否則會跳出錯誤:TypeError: replaceAll must be called with a global RegExp ## Logical assignment operator (IE不支援) (&&=)、 (||=)、 (??=) - And & Equals (&&=) ```jsx let a = 1; //------before 1 if(a){ a = 8; } //------before 2 a = a && 8 //------2021 a &&= 8 ``` - OR & Equals (||=) ```jsx let a = undefined; //-----before 1 if(!a){ a=5 } //-----before 2 a = a || 5 //-----2021 a||=5 ``` - Nullish Coalescing & Equals (??=) nullish: null and undefined (NOT 0 or '') ```jsx const a = { duration: 50 }; a.duration ??= 10; console.log(a.duration); // 50 a.speed ??= 25; console.log(a.speed); // 25 ``` ## Promise.any ie , opera 不支援 傳入 promise 組成的 array 作為参数 當有一個 promise 完成,就回傳完成結果, 當所有 promise 都被拒絕,則會回傳 AggregateError // AggregateError: All promises were rejected ```jsx // Promise.any [ES2021] Promise.any([ Promise.resolve('Success'), Promise.reject('ERROR'), Promise.resolve('Another success'), ]) .then(res => console.log(res)) .catch(err => console.error(err)); ``` ### Promise.all() 讓多個 promise 同時執行 傳入 promise 組成的 array 作為参数 所有 promise 都 resolve 才會回傳,但只要有其中一個 promise 被拒絕,則整個 Promise.all 立刻被拒絕 ```jsx const get3Countries = async function (c1, c2, c3) { try { // const [data1] = await getJSON( // `https://restcountries.eu/rest/v2/name/${c1}` // ); // const [data2] = await getJSON( // `https://restcountries.eu/rest/v2/name/${c2}` // ); // const [data3] = await getJSON( // `https://restcountries.eu/rest/v2/name/${c3}` // ); // console.log([data1.capital, data2.capital, data3.capital]); const data = await Promise.all([ getJSON(`https://restcountries.com/v2/name/${c1}?fullText=true`), getJSON(`https://restcountries.com/v2/name/${c2}?fullText=true`), getJSON(`https://restcountries.com/v2/name/${c3}?fullText=true`) ]); console.log(data.map((d) => d[0].capital)); } catch (err) { console.error(err); } }; get3Countries("portugal", "canada", "taiwan"); ``` ### Promise.allSettled() 傳入 promise 組成的 array 作為参数 所有的promise都已经`fulfilled`或`rejecte`後,回傳各自的結果 // Return [{status: "fulfilled",value: "Success"},...] ```javascript= // Promise.allSettled Promise.allSettled([ Promise.resolve('Success'), Promise.reject('ERROR'), Promise.resolve('Another success'), ]).then(res => console.log(res)); ``` Promise.all() vs **Promise.allSettled()** 非同步事件彼此**有相依關係**時使用Promise.all() **沒有相依關係的時候可以用 Promise.allSettled()** ### Promise.race() 傳入 promise 組成的 array 作為参数 立刻回傳第一個 fullfilled 或 rejected 的 promise 物件 ```jsx // javascript= (async function () { try { const res = await Promise.race([ getJSON(`https://restcountries.com/v2/name/portugal?fullText=true`), getJSON(`https://restcountries.com/v2/name/canada?fullText=true`), getJSON(`https://restcountries.com/v2/name/taiwan?fullText=true`) ]); console.log(res[0]); } catch (err) { console.error(err); } })(); // 實用的例子 Promise.race([ getJSON(`https://restcountries.com/v2/name/taiwan?fullText=true`), timeout(3) ]) .then((res) => console.log(res[0])) .catch((err) => console.error(err)); ``` ### The .at() array method (IE, safari on OS, Safari, opera mobile不支援) 帶入整數的正數或負數,回傳該位置的項目 負數會從最後一項開始往前數。 `at(index)` ```javascript= const arr = [23, 11, 64]; console.log(arr[0]); console.log(arr.at(0)); // getting last array element console.log(arr[arr.length - 1]); console.log(arr.slice(-1)[0]); console.log(arr.at(-1)); console.log('chi'.at(0)); console.log('chi'.at(-1)); ``` ### Intl :The **`Intl`** object is the namespace for the ECMAScript Internationalization API 主要用來**主要用途就是展示國際化信息,可以將字符串,數字和日期和時間轉換為指定地區的格式。 for language-sensitive functionalities.** ### **Intl.ListFormat** **把字符串連接成有意義的短語。** `new Intl.ListFormat(locales, options)` (IE 不支援) ```javascript= const list = ['Apple', 'Orange', 'Banana'] // Spanish console.log( new Intl.ListFormat('es', { style: 'long', type: 'conjunction' }).format(list) ) // Apple, Orange y Banana // German console.log( new Intl.ListFormat('de', { style: 'long', type: 'conjunction' }).format(list) ) // Apple, Orange und Banana ``` ### **Intl.DateTimeFormat** **將日期和時間格式化為指定語言的格式** `new Intl.DateTimeFormat(locales, options)` (IE 不支援) ```javascript= // short new Intl.DateTimeFormat('en', { timeStyle: 'short', }).format(Date.now()) // "2:45 PM" // medium new Intl.DateTimeFormat('ch', { timeStyle: 'medium', }).format(Date.now()) // 下午8:22:33 // long new Intl.DateTimeFormat('ch', { timeStyle: 'long', }).format(Date.now()) // 下午8:22:33 [GMT+8] ``` [https://codesandbox.io/s/es-2021-jnt0h](https://codesandbox.io/s/es-2021-jnt0h) NEXT [2022] coming soon... - Top-level await, Class Fields(private), Private Getters and setters, RegExp Match Indices , Accessible Object.prototype.hasOwnProperty