溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ES2021有哪些新功能

發(fā)布時間:2021-10-15 16:17:56 來源:億速云 閱讀:142 作者:iii 欄目:web開發(fā)

本篇內(nèi)容主要講解“ES2021有哪些新功能”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“ES2021有哪些新功能”吧!

簡述

ES2021(ES12)將于 2021  年中發(fā)布。在本文中,你將將會了解五個最有趣的功能:String.prototype.replaceAll(),數(shù)字分隔符,邏輯賦值運算符,Promise.any(),WeakRef  和Finalizers。

ES2021有哪些新功能

本文所描述的五個功能目前都處于第 4 階段。這意味著它們已經(jīng)完成,并將要在 JavaScript  引擎中實現(xiàn)了。這意味著你不會浪費時間去學(xué)習(xí)一些可能永遠也不會出現(xiàn)的東西。

這些功能不久將會發(fā)布。如果有興趣,可以到官方 Ecma TC39 GitHub (https://github.com/tc39/proposals)  去了解有關(guān)其他提案的更多信息。這個 Github 庫跟蹤了所有提案以及其當(dāng)前所處的階段。

String.prototype.replaceAll()

先從一個小功能 replaceAll() 開始,這是對 JavaScript  語言的一個補充。當(dāng)你要替換字符串中多次出現(xiàn)的匹配模式時,目前可以用 replace() 方法,但問題是它只能替換第一次出現(xiàn)的那個。

這并不意味著 replace() 不能替換所有出現(xiàn)的匹配模式,只不過你必須用正則表達式才行。如果你可以接受那就沒事兒了。不過對于很多 js  程序員來說,正則表達式并不是他們的菜(實際上是懶得學(xué)!)。

如果你就是這樣的 js 程序員,肯定喜歡新的 replaceAll() 方法。它的工作方式與 replace() 類似,區(qū)別在于 replaceAll()  可以不用正則表達式就能替換所有出現(xiàn)的模式。

replaceAll() 也能接受正則表達式,你完全可以用它代替 replace() 。

// 聲明一個字符串 let str = 'There are those who like cats, there those who like watching cats and there are those who have cats.'  // 用 dogs 替換所有的“cats”: strstr = str.replaceAll('cats', 'dogs') console.log(str) // Output: // 'There are those who like dogs, there those who like watching dogs and there are those who have dogs.'  // 用 replace() 的寫法: strstr = str.replace(/cats/g, 'dogs') console.log(str) // Output: // 'There are those who like dogs, there those who like watching dogs and there are those have dogs.'

數(shù)字分隔符

這是 JavaScript  ES2021的一個非常小的功能,可以讓你在處理大量數(shù)字時更好過一點。數(shù)字分隔符提供了一種能使大數(shù)字更易于閱讀和使用的簡單方法。語法也很簡單:一個下劃線  _。

// 不帶數(shù)字分隔符的 Number  const num = 3685134689  // 帶數(shù)字分隔符的 Number  const num = 3_685_134_689

不過數(shù)字分隔符只是在視覺上提供一些幫助。在使用時不會對數(shù)值本身產(chǎn)生任何影響。

// 帶數(shù)字分隔符的 Number  const num = 3_685_134_689  // 輸出: console.log(num) // Output: // 3685134689

邏輯賦值運算符

JavaScript 允許在布爾上下文中使用邏輯運算符。例如在 if ... else語句和三目運算符中檢測是 true 還是  false。ES2021 的邏輯賦值運算符將邏輯運算符與賦值表達式(=)組合在了一起。

在 JavaScript 中已經(jīng)有了一些賦值運算符,例如:加法賦值(+=),減法賦值(-=),乘法賦值(*=)等。在 ES2021 中又增加了對邏輯運算符  &&,|| 和 ??([空值合并)的支持。

////////////////// // 邏輯與賦值運算符 (&&=) ////////////////// x &&= y  // 以上代碼相當(dāng)于: xx = x && d // 或者: if (x) {   x = y }  // 例1: let x = 3  let y = 0  x &&= y console.log(x) // Output: // 0  // 例 2: let x = 0  let y = 9  x &&= y console.log(x) // Output: // 0  // 例 3: let x = 3 // Truthy value. let y = 15 // Truthy value. x &&= y console.log(x) // Output: // 15   ////////////////// // 邏輯或賦值運算符 (||=): x ||= y  // 相當(dāng)于: xx = x || y // 或者: if (!x) {   x = y }  // 例 1: let x = 3 let y = 0 x ||= y  console.log(x) // Output: // 3  // 例 2: let x = 0  let y = 9  x ||= y  console.log(x) // Output: // 9  // 例 3: let x = 3  let y = 15 x ||= y  console.log(x) // Output: // 3   ///////////////////////// // 空值合并賦值運算符 (??=): ///////////////////////// x ??= y  // 相當(dāng)于: xx = x ?? y // 或者: if (x == null || x == undefined) {     x = y }  // 例 1: let x = null  let y = 'Hello'  x ??= y console.log(x) // Output: // 'Hello'  // 例 2: let x = 'Jay'  let y = 'Hello'  x ??= y console.log(x) // Output: // 'Jay'  // 例 3: let x = 'Jay' let y = null  x ??= y console.log(x) // Output: // 'Jay'  // 例 4: let x = undefined  let y = 'Jock'  x ??= y  console.log(x) // Output: // 'Jock'

看一下上面的例子。首先是 x && = y。僅當(dāng) x 為真時,才將 y 賦值給 x。其次是 x || = y,僅當(dāng) x 為假時,才將 y  賦值給 x。如果 x 是真,而 y 是假,則不會進行賦值。

如果 x 和 y 都是假,也會發(fā)生同樣的情況。最后是 x ?? = y。僅當(dāng) x 為 null 或 undefined 時,才將 y 分配給 x。如果 x  既不是 null 也不是 undefined 則不會進行賦值,如果 y 為 null 或 undefined 也一樣。

Promise.any()

在 ES6 中引入了 Promise.race() 和 Promise.all() 方法,ES2020 加入了  Promise.allSettled()。ES2021 又增加了一個使 Promise 處理更加容易的方法:Promise.any() 。

Promise.any() 方法接受多個 promise,并在完成其中任何一個的情況下返回 promise。其返回的是 Promise.any()  完成的第一個 promise。如果所有 promise 均被拒絕,則 Promise.any() 將返回  AggregateError,其中包含拒絕的原因。

// 例 1: 全部被完成: // 創(chuàng)建 promises: const promise1 = new Promise((resolve, reject) => {   setTimeout(() => {     resolve('promise1 is resolved.')   }, Math.floor(Math.random() * 1000)) })  const promise2 = new Promise((resolve, reject) => {   setTimeout(() => {     resolve('promise2 is resolved.')   }, Math.floor(Math.random() * 1000)) })  const promise3 = new Promise((resolve, reject) => {   setTimeout(() => {     resolve('promise3 is resolved.')   }, Math.floor(Math.random() * 1000)) })  ;(async function() {   // Await the result of Promise.any():   const result = await Promise.any([promise1, promise2, promise3])   console.log(result)   // Output:   // 'promise1 is resolved.', 'promise2 is resolved.' or 'promise3 is resolved.' })()   // 例 2: 部分完成: const promise1 = new Promise((resolve, reject) => {   setTimeout(() => {     resolve('promise1 is resolved.')   }, Math.floor(Math.random() * 1000)) })  const promise2 = new Promise((resolve, reject) => {   setTimeout(() => {     reject('promise2 was rejected.')   }, Math.floor(Math.random() * 1000)) })  ;(async function() {   // Await the result of Promise.any():   const result = await Promise.any([promise1, promise2])   console.log(result)   // Output:   // 'promise1 is resolved.' })()   // 例 3: 均被拒絕: const promise1 = new Promise((resolve, reject) => {   setTimeout(() => {     reject('promise1 was rejected.')   }, Math.floor(Math.random() * 1000)) })  const promise2 = new Promise((resolve, reject) => {   setTimeout(() => {     reject('promise2 was rejected.')   }, Math.floor(Math.random() * 1000)) })  ;(async function() {   // Use try...catch to catch the AggregateError:   try {     // Await the result of Promise.any():     const result = await Promise.any([promise1, promise2])   }    catch (err) {     console.log(err.errors)     // Output:     // [ 'promise1 was rejected.', 'promise2 was rejected.' ]   } })()

弱引用:WeakRef

最后一個搶眼的功能是 WeakRefs。在 JavaScript 中,當(dāng)你創(chuàng)建了一個創(chuàng)建對象的引用時,這個引用可以防止對象被 gc  回收,也就是說 JavaScript 無法刪除對象并釋放其內(nèi)存。只要對該對象的引用一直存在,就可以使這個對象永遠存在。

ES2021 了新的類 WeakRefs。允許創(chuàng)建對象的弱引用。這樣就能夠在跟蹤現(xiàn)有對象時不會阻止對其進行垃圾回收。對于緩存和對象映射非常有用。

必須用 new關(guān)鍵字創(chuàng)建新的 WeakRef ,并把某些對象作為參數(shù)放入括號中。當(dāng)你想讀取引用(被引用的對象)時,可以通過在弱引用上調(diào)用 deref()  來實現(xiàn)。下面是一個非常簡單的例子。

const myWeakRef = new WeakRef({   name: 'Cache',   size: 'unlimited' })  console.log(myWeakRef.deref()) // Output: // { name: 'Cache', size: 'unlimited' }  console.log(myWeakRef.deref().name) // Output: // 'Cache'  console.log(myWeakRef.deref().size) // Output: // 'unlimited'

Finalizers 和 FinalizationRegistry

與 WeakRef 緊密相連的還有另一個功能,名為 finalizers 或  FinalizationRegistry。這個功能允許你注冊一個回調(diào)函數(shù),這個回調(diào)函數(shù)將會在對象被 gc 回收時調(diào)用。

// 創(chuàng)建 FinalizationRegistry: const reg = new FinalizationRegistry((val) => {   console.log(val) })  ;(() => {   // 創(chuàng)建新對象:   const obj = {}    //為 “obj” 對象注冊 finalizer:   //第一個參數(shù):要為其注冊 finalizer 的對象。   //第二個參數(shù):上面定義的回調(diào)函數(shù)的值。   reg.register(obj, 'obj has been garbage-collected.') })() // 當(dāng) "obj" 被gc回收時輸出: // 'obj has been garbage-collected.'

官方建議不要輕易使用 WeakRef 和 finalizer。其中一個原因是它們可能不可預(yù)測,另一個是它們并沒有真正幫 gc  完成工作,實際上可能會gc的工作更加困難。你可以在它的提案(https://github.com/tc39/proposal-weakrefs#a-note-of-caution)中詳細了解其原因。

到此,相信大家對“ES2021有哪些新功能”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

es
AI