欢迎访问 生活随笔!

凯发k8官方网

当前位置: 凯发k8官方网 > 前端技术 > javascript >内容正文

javascript

javascript es2021 最值得期待的 5 个新特性解析 -凯发k8官方网

发布时间:2025/1/21 javascript 16 豆豆
凯发k8官方网 收集整理的这篇文章主要介绍了 javascript es2021 最值得期待的 5 个新特性解析 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

在写本文时,本文提到的新的 javascript 提案功能已进入第 4 阶段,并且几乎肯定会包含在 es2021 中。你已经可以开始在 最新版本的浏览器,node.js 和 babel 中使用。

注意:ecmascript 是 javascript 所基于的标准,由 tc39 委员会管理。ecmascript 始终是一个不需要的名称,这会使一切都对初学者感到困惑。人们经常谈论 javascript 功能,但参考的是 ecmascript 规范。

更新特性

  • 数字分隔符(_)

  • 逻辑分配(&&=,||=,??=)

  • 引用不足(weakref和finalizationregistry)

  • promise.any

  • string.prototype.replaceall

1. 数值分隔符

大数字文字很难使人眼快速解析,尤其是当有很多重复的数字时:

1000000000000   1019436871.42

为了提高可读性,新的 javascript 语言功能 启用了下划线作为数字文字中的分隔符。因此,上面的内容现在可以重写为每千位数字,例如:

1_000_000_000_000    1_019_436_871.42

现在,更容易说出第一个数字是 1 万亿,而第二个数字大约是 10 亿。

数字分隔符有助于提高各种数字文字的可读性:

// a decimal integer literal with its digits grouped per thousand: 1_000_000_000_000 // a decimal literal with its digits grouped per thousand: 1_000_000.220_720 // a binary integer literal with its bits grouped per octet: 0b01010110_00111000 // a binary integer literal with its bits grouped per nibble: 0b0101_0110_0011_1000 // a hexadecimal integer literal with its digits grouped by byte: 0x40_76_38_6a_73 // a bigint literal with its digits grouped per thousand: 4_642_473_943_484_686_707n

它们甚至适用于八进制整数文字(尽管 我想不出 其中分隔符为此类文字提供值 的示例):

// a numeric separator in an octal integer literal: ????‍♀️ 0o123_456

请注意,javascript 还具有不带显式 0o 前缀的八进制文字的旧式语法。例如,017 === 0o17。在严格模式下或模块内不支持此语法,并且在现代代码中不应使用此语法。因此,这些文字不支持数字分隔符。使用 0o17 风格的文字代替。

2. promise combinators

自从 es2015 中引入 promise 以来,javascript 完全支持两种 promise 组合器:静态方法 promise.all 和 promise.race。

目前有两个新提案正在通过标准化流程:promise.allsettled 和 promise.any。有了这些添加,javascript 中将总共有四个诺言组合器,每个组合器支持不同的用例。

以下是这四个组合器的概述:

2.1 promise.allsettled

promise.allsettled 给你当所有输入的诺言是一种信号结算,这意味着他们要么履行或拒绝。如果您不在乎承诺的状态,而只是想知道工作何时完成,无论它是否成功,这都是很有用的。

例如,您可以启动一系列独立的 api 调用,并使用 promise.allsettled 它们来确保它们已全部完成,然后再执行其他操作,例如删除加载微调器:

const promises = [fetch('/api-call-1'),fetch('/api-call-2'),fetch('/api-call-3'), ]; // imagine some of these requests fail, and some succeed.await promise.allsettled(promises); // all api calls have finished (either failed or succeeded). removeloadingindicator();

2.2 promise.any

promise.any 方法和 promise.race 类似——只要给定的迭代中的一个 promise 成功,就采用第一个 promise 的值作为它的返回值,但与 promise.race 的不同之处在于——它会等到所有 promise 都失败之后,才返回失败的值:

const promises = [fetch('/endpoint-a').then(() => 'a'),fetch('/endpoint-b').then(() => 'b'),fetch('/endpoint-c').then(() => 'c'), ]; try {const first = await promise.any(promises);// any of the promises was fulfilled.console.log(first);// → e.g. 'b' } catch (error) {// all of the promises were rejected.console.assert(error instanceof aggregateerror);// log the rejection values:console.log(error.errors);// → [//     ,//     ,//     //   ] }

此代码示例检查哪个端点响应最快,然后将其记录下来。只有当 所有 请求都失败时,我们才最终进入代码 catch 块,然后在其中处理错误。

promise.any 拒绝可以一次代表多个错误。为了在语言级别支持此功能,引入了一种新的错误类型,称为 aggregateerror。除了上面示例中的基本用法外,还可以以编程方式构造 aggregateerror 对象,就像其他错误类型一样:

const aggregateerror = new aggregateerror([errora, errorb, errorc], 'stuff went wrong!');

3. weak references and finalizers

此功能包含两个高级对象 weakref 和 finalizationregistry。根据使用情况,这些接口可以单独使用,也可以一起使用。正确使用它们需要仔细考虑,如果可能,最好避免使用它们。

一般来说,在javascript中,对象的引用是强保留的,这意味着只要持有对象的引用,它就不会被垃圾回收。

const ref = { x: 42, y: 51 }; // 只要我们访问 ref 对象(或者任何其他引用指向该对象),这个对象就不会被垃圾回收

目前在 javascript 中,weakmap 和 weakset 是弱引用对象的唯一方法:将对象作为键添加到 weakmap 或 weakset 中,是不会阻止它被垃圾回收的。

javascript 的 weakmap 并不是真正意义上的弱引用:实际上,只要键仍然存活,它就强引用其内容。weakmap 仅在键被垃圾回收之后,才弱引用它的内容。

weakref 是一个更高级的 api,它提供了真正的弱引用,weakref 实例具有一个方法 deref,该方法返回被引用的原始对象,如果原始对象已被收集,则返回 undefined 对象。

javascript 中对象的引用是强引用,weakmap 和 weakset 可以提供部分的弱引用功能,若想在 javascript 中实现真正的弱引用,可以通过配合使用 weakref 和终结器(finalizer)来实现。

weakref 是用来指目标对象不脱离垃圾收集保留它的对象。如果未通过垃圾回收回收目标对象,则 weakrefs 可以取消引用以允许访问目标对象。

// create a weakref object referring to a given target object const ref = new weakref(targetobject)// return the weakref instance's target object, or undefined if the target object has been garbage-collected const obj = ref.deref()

使用 finalizationregistry 对象可以在垃圾回收对象时请求回调。

// create a registry object that uses the given callback const registry = new finalizationregistry([callback])// register an object with a registry instance so that if the object is garbage-collected, the registry's callback may get called registry.register(target, heldvalue, [unregistertoken])// unregister a target object from a registry instance registry.unregister(unregistertoken)

更多信息:tc39提案,v8

4. string.prototype.replaceall

当前,如果不使用全局正则表达式,就无法替换字符串中子字符串的所有实例。与字符串参数一起使用时,string.prototype.replace 仅影响首次出现。

string.prototype.replaceall() 将为开发人员提供一种简单的方法来完成此常见的基本操作。

'aabbcc'.replaceall('b', '.') // 'aa..cc' 'aabbcc'.replaceall(/b/g, '.') // 'aa..cc'

5. logical assignment (逻辑分配)

支持与新的运营逻辑分配 &&=,||= 和 ??=。与它们的 数学和按位对应物不同,逻辑分配遵循其各自逻辑操作的短路行为。仅当逻辑运算将评估右侧时,它们才执行分配。

// falsy: false, 0, -0, 0n, "", null, undefined, and nan // truthy: all values are truthy unless defined as falsy // nullish: null or undefineda ||= b // logical or assignment // equivalent to: a || (a = b); // only assigns if a is falsya &&= b // logical and assignment // equivalent to: a && (a = b); // only assigns if a is truthya ??= b // logical nullish assignment // equivalent to: a ?? (a = b); // only assigns if a is nullish

5.1 具体例子

带有 && 运算符的逻辑赋值运算符

仅当 lhs 值为真时,才将 rhs 变量值赋给 lhs 变量。

// logical assignment operator with && operator let num1 = 5 let num2 = 10 num1 &&= num2 console.log(num1) // 10 // line 5 can also be written as following ways // 1. num1 && (num1 = num2) // 2. if (num1) num1 = num2

带有 || 的运算符逻辑赋值运算符

仅当 lhs 值为假时,才将 rhs 变量值赋给 lhs 变量。

// logical assignment operator with || operator let num1 let num2 = 10 num1 ||= num2 console.log(num1) // 10 // line 5 can also be written as following ways // 1. num1 || (num1 = num2) // 2. if (!num1) num1 = num2

带有 ?? 运算符的逻辑赋值运算符

es2020 引入了空值合并运算符,其也可以与赋值运算符结合使用。仅当 lhs 为 undefined 或仅为 null 时,才将 rhs 变量值赋给 lhs 变量。

// logical assignment operator with ?? operator let num1 let num2 = 10 num1 ??= num2 console.log(num1) // 10 num1 = false num1 ??= num2 console.log(num1) // false // line 5 can also be written as following ways // num1 ?? (num1 = num2)

概括

作为开发人员,跟紧语言的新特性是很重要的。

以上将在 2021 年发布的一些新功能,它们是进入第 4 阶段的提案,几乎可以肯定会包括在内,这些功能已经在最新的浏览器和 babel 中实现。

参考文章:javascript features in 2021

可以加猫哥的 wx:cb834301747 ,一起闲聊前端。

微信搜 “全栈修炼”,回复 “电子书” 即可以获得 300 本前端精华书籍哦。

往期精文

  • vue3 全家桶 element plus vite typescript eslint 项目配置最佳实践

  • typescript 中提升幸福感的 10 个高级技巧

  • 推荐 7 个 vue2、vue3 源码解密分析的重磅开源项目

通过阅读本篇文章,如果有收获的话,可以点个赞在看,这将会成为我持续分享的动力,感谢~

总结

以上是凯发k8官方网为你收集整理的javascript es2021 最值得期待的 5 个新特性解析的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得凯发k8官方网网站内容还不错,欢迎将凯发k8官方网推荐给好友。

网站地图