ES2021是2021年的ECMAScript版本。ES2021并没有像ES2015那样提出那么多的新特性,但是包含了一些有用的特性。本文将通过通俗易懂的代码示例介绍ES2021的新特性。当然,在此之前,你需要了解JavaScript的基础知识。下面是ES2021新特性的概述:String.prototype.replaceAllPromise.anyWeakRef逻辑赋值运算符数字分隔符String.protype.replaceAll在ES2021之前,要替换一个字符串中的所有指定字符,我们可以这样做:constfruits='🍎+🍐+🍓+';constfruitsfruitsWithBanana=fruits.replace(/\+/g,'🍌');console.log(fruitsWithBanana);//🍎🍌🍐ES2021提出了replaceAll方法,挂载在String的原型上,可以这样使用:constfruits='🍎+🍐+🍓+';constfruitsfruitsWithBanana=fruits.replaceAll('+','🍌');console.log(fruitsWithBanana);//🍎🍌🍐🍌🍓🍌Promise.anyPromise.any方法类似于Promise.race——每当给定迭代中的一个promise成功时,将第一个promise的值作为它的返回值,但不同于Promise.race的一点是——它会等待直到所有承诺在返回失败值之前失败:constmyFetch=url=>setTimeout(()=>fetch(url),Math.floor(Math.random()*3000));constpromises=[myFetch('/endpoint-1'),myFetch('/endpoint-2'),myFetch('/endpoint-3'),];//使用.then.catchPromise.any(promises)//任意一承诺成功。.then(console.log)//如'3'.catch(console.error);//所有promise都失败了//使用async-awaittry{constfirst=awaitPromise.any(promises);//任何promise成功返回.console.log(first);}catch(error){//Allpromiseshavefailedconsole.log(error);}WeakRefWeakRef提案主要包含两个新功能:可以通过WeakRef类References为一个对象创建weakobjectReferences即可通过FinalizationRegistry类进行。对象被垃圾回收后,会执行一些自定义方法。以上两个新功能可以同时使用,也可以分开使用,看你的需要。WeakRef对象包含对对象的弱引用,称为目标或引用。通过弱引用一个对象,当没有其他引用时,该对象可以被垃圾回收机制回收。WeakRef主要用来缓存和映射一些大对象。当你希望一个对象被及时垃圾回收而不被其他地方引用时,你可以使用它。functiontoogle(元素){constweakElement=newWeakRef(元素);letintervalId=null;functiontoggle(){constel=weakElement.deref();if(!el){returnclearInterval(intervalId);}constdecoration=weakElement.style.textDecoration;conststyle=decoration==='none'?'underline':'none';decoration=style;}intervalId=setInterval(toggle,1000);}constelement=document.getElementById("link");toogle(element);setTimeout(()=>element.remove(),10000);FinalizationRegistry接收注册回调函数,可用于为指定对象注册事件监听器。当对象被垃圾回收时,将触发监视事件。具体步骤如下。首先,创建注册表:constregistry=newFinalizationRegistry(heldValue=>{//...});然后注册一个指定的对象,也可以给注册回调传递一些参数:registry.register(theObject,"somevalue");逻辑赋值运算符译者注:赋值运算符和表达式的区别可以看这里。逻辑赋值运算符结合了逻辑运算符和赋值表达式。逻辑赋值运算符有两种:或等于(||=)和等于(&&=)//或等于|a|b|a||=b|a(运算后)||true|true|true|true||true|false|true|true||false|true|true|true||false|false|false|false|a||=b//等于:a||(a=b);//andEqualto|a|b|a&&=b|a(运算后)||true|true|true|true||true|false|false|false||false|true|false|false||false|假|假|false|a&&=b//等价于:a&&(a=b);numberseparator通过这个函数,我们使用“(_,U+005F)”分隔符对数字进行分组,提高数字的可读性:1_000_000_000//十亿101_475_938.38//亿constamount=12345_00;//12,345constamount=123_4500;//123.45(4decimalplaces)constamount=1_234_500;//1,234,5000.000_001//onemillionth1e10_000//10^10000constbinary_literals=0b1010_0001_1000_0101;consthex_literals=0xA0_B0_C0;constbigInt_literals=1_000_000_000_000n;constoctal_literal=0o1234_5670;SummaryJavaScriptisadynamically在某些方面有利于Web开发的类型化语言JavaScript自ES2015以来发展迅速。在本文中,我们重点回顾ES2021的一些新特性。虽然你的项目可能不会用到这些新特性,但它们确实为项目开发提供了多种可能,不是吗?
