自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

即將發(fā)布的 ES2021 中有哪些有趣的功能

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

本文轉載自微信公眾號“前端先鋒”(jingchengyideng)。

簡述

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

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

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

String.prototype.replaceAll()

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

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

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

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

  1. // 聲明一個字符串 
  2. let str = 'There are those who like cats, there those who like watching cats and there are those who have cats.' 
  3.  
  4. // 用 dogs 替換所有的“cats”: 
  5. strstr = str.replaceAll('cats', 'dogs') 
  6. console.log(str) 
  7. // Output: 
  8. // 'There are those who like dogs, there those who like watching dogs and there are those who have dogs.' 
  9.  
  10. // 用 replace() 的寫法: 
  11. strstr = str.replace(/cats/g, 'dogs') 
  12. console.log(str) 
  13. // Output: 
  14. // 'There are those who like dogs, there those who like watching dogs and there are those have dogs.' 

數(shù)字分隔符

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

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

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

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

邏輯賦值運算符

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

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

  1. ////////////////// 
  2. // 邏輯與賦值運算符 (&&=) 
  3. ////////////////// 
  4. x &&= y 
  5.  
  6. // 以上代碼相當于: 
  7. xx = x && d 
  8. // 或者: 
  9. if (x) { 
  10.   x = y 
  11.  
  12. // 例1: 
  13. let x = 3  
  14. let y = 0  
  15. x &&= y 
  16. console.log(x) 
  17. // Output: 
  18. // 0 
  19.  
  20. // 例 2: 
  21. let x = 0  
  22. let y = 9  
  23. x &&= y 
  24. console.log(x) 
  25. // Output: 
  26. // 0 
  27.  
  28. // 例 3: 
  29. let x = 3 // Truthy value. 
  30. let y = 15 // Truthy value. 
  31. x &&= y 
  32. console.log(x) 
  33. // Output: 
  34. // 15 
  35.  
  36.  
  37. ////////////////// 
  38. // 邏輯或賦值運算符 (||=): 
  39. x ||= y 
  40.  
  41. // 相當于: 
  42. xx = x || y 
  43. // 或者: 
  44. if (!x) { 
  45.   x = y 
  46.  
  47. // 例 1: 
  48. let x = 3 
  49. let y = 0 
  50. x ||= y 
  51.  
  52. console.log(x) 
  53. // Output: 
  54. // 3 
  55.  
  56. // 例 2: 
  57. let x = 0  
  58. let y = 9  
  59. x ||= y 
  60.  
  61. console.log(x) 
  62. // Output: 
  63. // 9 
  64.  
  65. // 例 3: 
  66. let x = 3  
  67. let y = 15 
  68. x ||= y 
  69.  
  70. console.log(x) 
  71. // Output: 
  72. // 3 
  73.  
  74.  
  75. ///////////////////////// 
  76. // 空值合并賦值運算符 (??=): 
  77. ///////////////////////// 
  78. x ??= y 
  79.  
  80. // 相當于: 
  81. xx = x ?? y 
  82. // 或者: 
  83. if (x == null || x == undefined) { 
  84.     x = y 
  85.  
  86. // 例 1: 
  87. let x = null  
  88. let y = 'Hello'  
  89. x ??= y 
  90. console.log(x) 
  91. // Output: 
  92. // 'Hello' 
  93.  
  94. // 例 2: 
  95. let x = 'Jay'  
  96. let y = 'Hello'  
  97. x ??= y 
  98. console.log(x) 
  99. // Output: 
  100. // 'Jay' 
  101.  
  102. // 例 3: 
  103. let x = 'Jay' 
  104. let y = null  
  105. x ??= y 
  106. console.log(x) 
  107. // Output: 
  108. // 'Jay' 
  109.  
  110. // 例 4: 
  111. let x = undefined  
  112. let y = 'Jock'  
  113. x ??= y 
  114.  
  115. console.log(x) 
  116. // Output: 
  117. // 'Jock' 

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

如果 x 和 y 都是假,也會發(fā)生同樣的情況。最后是 x ?? = y。僅當 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. // 例 1: 全部被完成: 
  2. // 創(chuàng)建 promises: 
  3. const promise1 = new Promise((resolve, reject) => { 
  4.   setTimeout(() => { 
  5.     resolve('promise1 is resolved.') 
  6.   }, Math.floor(Math.random() * 1000)) 
  7. }) 
  8.  
  9. const promise2 = new Promise((resolve, reject) => { 
  10.   setTimeout(() => { 
  11.     resolve('promise2 is resolved.') 
  12.   }, Math.floor(Math.random() * 1000)) 
  13. }) 
  14.  
  15. const promise3 = new Promise((resolve, reject) => { 
  16.   setTimeout(() => { 
  17.     resolve('promise3 is resolved.') 
  18.   }, Math.floor(Math.random() * 1000)) 
  19. }) 
  20.  
  21. ;(async function() { 
  22.   // Await the result of Promise.any(): 
  23.   const result = await Promise.any([promise1, promise2, promise3]) 
  24.   console.log(result) 
  25.   // Output: 
  26.   // 'promise1 is resolved.', 'promise2 is resolved.' or 'promise3 is resolved.' 
  27. })() 
  28.  
  29.  
  30. // 例 2: 部分完成: 
  31. const promise1 = new Promise((resolve, reject) => { 
  32.   setTimeout(() => { 
  33.     resolve('promise1 is resolved.') 
  34.   }, Math.floor(Math.random() * 1000)) 
  35. }) 
  36.  
  37. const promise2 = new Promise((resolve, reject) => { 
  38.   setTimeout(() => { 
  39.     reject('promise2 was rejected.') 
  40.   }, Math.floor(Math.random() * 1000)) 
  41. }) 
  42.  
  43. ;(async function() { 
  44.   // Await the result of Promise.any(): 
  45.   const result = await Promise.any([promise1, promise2]) 
  46.   console.log(result) 
  47.   // Output: 
  48.   // 'promise1 is resolved.' 
  49. })() 
  50.  
  51.  
  52. // 例 3: 均被拒絕: 
  53. const promise1 = new Promise((resolve, reject) => { 
  54.   setTimeout(() => { 
  55.     reject('promise1 was rejected.') 
  56.   }, Math.floor(Math.random() * 1000)) 
  57. }) 
  58.  
  59. const promise2 = new Promise((resolve, reject) => { 
  60.   setTimeout(() => { 
  61.     reject('promise2 was rejected.') 
  62.   }, Math.floor(Math.random() * 1000)) 
  63. }) 
  64.  
  65. ;(async function() { 
  66.   // Use try...catch to catch the AggregateError: 
  67.   try { 
  68.     // Await the result of Promise.any(): 
  69.     const result = await Promise.any([promise1, promise2]) 
  70.   } 
  71.  
  72.   catch (err) { 
  73.     console.log(err.errors) 
  74.     // Output: 
  75.     // [ 'promise1 was rejected.', 'promise2 was rejected.' ] 
  76.   } 
  77. })() 

弱引用:WeakRef

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

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

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

  1. const myWeakRef = new WeakRef({ 
  2.   name: 'Cache', 
  3.   size: 'unlimited' 
  4. }) 
  5.  
  6. console.log(myWeakRef.deref()) 
  7. // Output: 
  8. // { name: 'Cache', size: 'unlimited' } 
  9.  
  10. console.log(myWeakRef.deref().name) 
  11. // Output: 
  12. // 'Cache' 
  13.  
  14. console.log(myWeakRef.deref().size) 
  15. // Output: 
  16. // 'unlimited' 

Finalizers 和 FinalizationRegistry

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

  1. // 創(chuàng)建 FinalizationRegistry: 
  2. const reg = new FinalizationRegistry((val) => { 
  3.   console.log(val) 
  4. }) 
  5.  
  6. ;(() => { 
  7.   // 創(chuàng)建新對象: 
  8.   const obj = {} 
  9.  
  10.   //為 “obj” 對象注冊 finalizer: 
  11.   //第一個參數(shù):要為其注冊 finalizer 的對象。 
  12.   //第二個參數(shù):上面定義的回調(diào)函數(shù)的值。 
  13.   reg.register(obj, 'obj has been garbage-collected.') 
  14. })() 
  15. // 當 "obj" 被gc回收時輸出: 
  16. // 'obj has been garbage-collected.' 

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

總結

與以前的 JavaScript 規(guī)范(例如 ES6 和 ES2020)相比,看上去 ES2021的更新不多,但是這些有趣的功能值得我們關注。

 

責任編輯:趙寧寧 來源: 前端先鋒
相關推薦

2023-11-24 08:31:03

ECMAScriptES2021

2021-09-04 05:00:26

ESES2021ES12

2009-10-23 14:22:59

Windows 7微軟隱藏功能

2020-07-29 10:00:38

PythonEllipsis索引

2023-05-22 16:03:00

Javascript開發(fā)前端

2020-10-14 13:12:19

Windows 10操作系統(tǒng)微軟

2020-07-26 12:01:08

PythonPython 3.8開發(fā)

2018-03-05 11:10:10

Android P工程師谷歌

2018-03-04 08:37:17

谷歌Android開發(fā)者

2023-08-13 16:32:12

JavaScript

2022-04-02 10:31:32

ThunderbirLinux

2020-11-23 11:34:52

ES6

2016-11-22 14:12:13

2025-03-19 09:55:17

2024-10-18 14:52:16

2011-01-26 11:38:37

BlackBerry

2021-03-03 12:33:31

微軟Windows SerInsider

2022-07-07 15:50:19

Python開發(fā)功能

2021-02-04 09:52:30

增強現(xiàn)實AR數(shù)字通信

2024-04-29 13:54:12

iOS 18蘋果
點贊
收藏

51CTO技術棧公眾號