ECMAScript2022是一项新的JavaScript标准,将于2022年6月发布。 1。数组中的at()方法 ES2022将为我们提供一种可能性,即从末端索引类似数组的对象。这是一个很小的功能,但它提高了处理数组或字符串时的核心可读性。 At()方法中的正数与〔〕索引的作用相同,但如果是负数,则允许从末尾访问数值。 原来:constarr〔1,2,3,4〕arr〔arr。length2〕3arr。slice(2)〔0〕3conststr1234str〔str。length2〕3str。slice(2)〔0〕3 新的at()方法:constarr〔1,2,3,4〕arr。at(2)3conststr1234str。at(2)3 2。错误原因 。cause对象上的。cause属性将允许我们指定哪个错误导致其他错误。非常不言而喻吧?在这里你可以看到这个新功能的一个使用例子。try{doSomeComputationThatThrowAnError()}catch(error){thrownewError(Iamtheresultofanothererror,{cause:error})} 错误原因将是一个完美的方法,可以将错误连在一起,这在其他编程语言如Java中是可能的。 3。顶层的await 你知道你不能在函数之外的代码中直接使用await吗?如果不知道,那么这对你来说不是什么大问题。但对于其他人来说不必担心,因为ES2022将改变这一点。它允许动态地加载模块constserviceNameawaitfetch(https:example。comwhatserviceshouldiuse)constserviceawaitimport(services{serviceName}。js)ORconstparamsnewURLSearchParams(location。search);constthemeparams。get(theme);conststylingFunctionsawaitimport(stylingfunctions{theme}。js);它允许有条件地渲染模块constdatenewDate()if(date。getFullYear()2023){awaitrequire(specialcodefor2023year。js)} 4。私有槽slot和方法 纯Javascript中的类从ES6开始就存在了,但与面向对象的语言相比,它们的开发程度要低很多。许多开发者使用Typescript来包含其中的一些功能,现在我们可以看到在纯Javascript类中被实现。 私有槽是其中之一。它们只不过是类的私有属性。ES2022将为我们提供创建它们的可能性,当我们试图在类之外访问它们时,会得到一个错误。私有方法也是如此。有趣的是,JS团队选择给他们前缀(这与JS的传统有关吗?)classHuman{nameJsetName(name){this。}}consthumannewHuman()human。nameAmyERROR!human。setName(Amy)OK 私有方法:classHuman{nameJconstructor(name){this。setName(Amy)OK}setName(name){this。}}consthumannewHuman()human。setName(Amy)ERROR! ES2022中的4个最重要的特性