即将发布的 ES2021 中有哪些有趣的功能

开发 前端
在本文中,你将将会了解五个最有趣的功能:String.prototype.replaceAll(),数字分隔符,逻辑赋值运算符,Promise.any(),WeakRef 和Finalizers。

本文转载自微信公众号“前端先锋”(jingchengyideng)。

简述

ES2021(ES12)将于 2021 年中发布。在本文中,你将将会了解五个最有趣的功能:String.prototype.replaceAll(),数字分隔符,逻辑赋值运算符,Promise.any(),WeakRef 和Finalizers。

本文所描述的五个功能目前都处于第 4 阶段。这意味着它们已经完成,并将要在 JavaScript 引擎中实现了。这意味着你不会浪费时间去学习一些可能永远也不会出现的东西。

这些功能不久将会发布。如果有兴趣,可以到官方 Ecma TC39 GitHub (https://github.com/tc39/proposals) 去了解有关其他提案的更多信息。这个 Github 库跟踪了所有提案以及其当前所处的阶段。

String.prototype.replaceAll()

先从一个小功能 replaceAll() 开始,这是对 JavaScript 语言的一个补充。当你要替换字符串中多次出现的匹配模式时,目前可以用 replace() 方法,但问题是它只能替换第一次出现的那个。

这并不意味着 replace() 不能替换所有出现的匹配模式,只不过你必须用正则表达式才行。如果你可以接受那就没事儿了。不过对于很多 js 程序员来说,正则表达式并不是他们的菜(实际上是懒得学!)。

如果你就是这样的 js 程序员,肯定喜欢新的 replaceAll() 方法。它的工作方式与 replace() 类似,区别在于 replaceAll() 可以不用正则表达式就能替换所有出现的模式。

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.' 

数字分隔符

这是 JavaScript ES2021的一个非常小的功能,可以让你在处理大量数字时更好过一点。数字分隔符提供了一种能使大数字更易于阅读和使用的简单方法。语法也很简单:一个下划线 _。

  1. // 不带数字分隔符的 Number  
  2. const num = 3685134689 
  3.  
  4. // 带数字分隔符的 Number  
  5. const num = 3_685_134_689 

不过数字分隔符只是在视觉上提供一些帮助。在使用时不会对数值本身产生任何影响。

  1. // 带数字分隔符的 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 中已经有了一些赋值运算符,例如:加法赋值(+=),减法赋值(-=),乘法赋值(*=)等。在 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 都是假,也会发生同样的情况。最后是 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. // 创建 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 中,当你创建了一个创建对象的引用时,这个引用可以防止对象被 gc 回收,也就是说 JavaScript 无法删除对象并释放其内存。只要对该对象的引用一直存在,就可以使这个对象永远存在。

ES2021 了新的类 WeakRefs。允许创建对象的弱引用。这样就能够在跟踪现有对象时不会阻止对其进行垃圾回收。对于缓存和对象映射非常有用。

必须用 new关键字创建新的 WeakRef ,并把某些对象作为参数放入括号中。当你想读取引用(被引用的对象)时,可以通过在弱引用上调用 deref() 来实现。下面是一个非常简单的例子。

  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。这个功能允许你注册一个回调函数,这个回调函数将会在对象被 gc 回收时调用。

  1. // 创建 FinalizationRegistry: 
  2. const reg = new FinalizationRegistry((val) => { 
  3.   console.log(val) 
  4. }) 
  5.  
  6. ;(() => { 
  7.   // 创建新对象: 
  8.   const obj = {} 
  9.  
  10.   //为 “obj” 对象注册 finalizer: 
  11.   //第一个参数:要为其注册 finalizer 的对象。 
  12.   //第二个参数:上面定义的回调函数的值。 
  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 规范(例如 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开发前端

2020-10-14 13:12:19

Windows 10操作系统微软

2020-07-26 12:01:08

PythonPython 3.8开发

2018-03-05 11:10:10

Android P工程师谷歌

2018-03-04 08:37:17

谷歌Android开发者

2022-04-02 10:31:32

ThunderbirLinux

2023-08-13 16:32:12

JavaScript

2016-11-22 14:12:13

2020-11-23 11:34:52

ES6

2011-01-26 11:38:37

BlackBerry

2021-03-03 12:33:31

微软Windows SerInsider

2022-07-07 15:50:19

Python开发功能

2020-10-16 18:53:00

Windows微软操作系统

2017-09-06 15:14:25

苹果发布iOS 11

2010-03-12 10:30:18

Python语言

2009-08-25 14:25:19

Eclipse 3.5
点赞
收藏

51CTO技术栈公众号