• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • ECMAScript 2021(ES12)新特性

    ECMAScript 2021(ES12)新特性:

    • String.prototype.replaceAll():有了这个 API,替换字符不用写正则了。
    • Promise.any():返回第一个 fullfilled 的 promise ,若全部 reject,则返回一个带有失败原因的 AggregateError。
    • 新增逻辑赋值操作符:??=&&=||=
    • WeakRefs:使用弱引用对象,该弱引用不会阻止 GC,并且可以在 GC 前使用 WeakRef.prototype.deref()解除该引用。
    • _(下划线)分隔符:分隔数字字面量以方便阅读。
    • Intl.ListFormat:用来处理和多语言相关的对象格式化操作。
    • Intl.DateTimeFormat API 中的dateStyletimeStyle的配置项:用来处理多语言下的时间日期格式化的函数。


    replaceAll

    模式的所有匹配都会被替代项替换。模式可以是字符串或正则表达式,而替换项可以是字符串或针对每次匹配执行的函数。并返回一个全新的字符串

    在没有这个特性之前,我们会这样写

    const str = "student is a real student";
    const newStr = str.replace(/student/g, "hahaha");
    console.log(newStr); 
    

    有了replaceAll之后我们可以这么写了

    const str = "student is a real student";
    const newStr = str.replaceAll('student', "hahaha");
    console.log(newStr); 
    

    最终运行的结果都是:hahaha is a real hahaha


    Promise.any

    可以把 Promise.any 理解成 Promise.all 的相反操作。Promise.any 也可以接受一个 Promise 数组,当其中任何一个 Promise 完成(fullfill)时,就返回那个已经有完成值的 Promise。如果所有的 Promise 都拒绝(reject),则返回一个拒绝的 Promise,该 Promise 的返回值是一个 AggregateError 对象。

    例如下面有三个 Promise 请求正常情况下:

    const p1 = new Promise((resolve, reject) => {
      setTimeout(() => resolve("A"), Math.floor(Math.random() * 1000));
    });
    const p2 = new Promise((resolve, reject) => {
      setTimeout(() => resolve("B"), Math.floor(Math.random() * 1000));
    });
    const p3 = new Promise((resolve, reject) => {
      setTimeout(() => resolve("C"), Math.floor(Math.random() * 1000));
    });
    (async function () {
      const result = await Promise.any([p1, p2, p3]);
      console.log(result); // 输出结果可能是 "A", "B" 或者 "C"
    })();
    

    如果存在某个 Promise 发生错误的情况:

    const p = new Promise((resolve, reject) => reject());
    try {
      (async function () {
        const result = await Promise.any([p]);
        console.log(result);
      })();
    } catch (error) {
      console.log(error.errors);
    }
    


    逻辑赋值操作符:??=、&&=、||=

    看下如下代码:

    let a = 1;
    a = a + 2;
    

    可以简写为:

    let a = 1;
    a += 2;
    

    有了这个新的标准中,逻辑表达式的操作符(&&||??)也可以简写了!

    先来介绍下??,它是去年发布的标准中的新的逻辑操作符。大家可能遇到过,如果一个变量是空,需要给它赋值为一个默认值的情况。通常我们会这样写:

    let num = number || 222
    

    但是,以上的代码会有一个 bug。如果realCount的值是0,则会被当作取不到其值,会取到'无法获取'这个字符串。而如果我们使用了??,只有当操作符左边的值是null或者undefined的时候,才会取操作符右边的值:

    let num = number ?? 222
    

    接下来,再来看下新标准中的逻辑运算符怎么用:

    // 等同于 a = a || b
    a ||= b;
    // 等同于 c = c && d
    c &&= d;
    // 等同于 e = e ?? f
    e ??= f;
    


    WeakRef

    WeakRef是一个 Class,一个WeakRef对象可以让你拿到一个对象的弱引用。这样,就可以不用阻止垃圾回收这个对象了。可以使用其构造函数来创建一个WeakRef对象。

    // anObject 不会因为 ref 引用了这个对象,而不会被垃圾回收
    let ref = new WeakRef(anObject);
    

    我们可以用WeakRef.prototype.deref()来取到anObject的值。但是,在被引用对象被垃圾回收之后,这个函数就会返回undefined

    // 如果 someObj 被垃圾回收了,则 obj 就会是 undefined
    let obj = ref.deref();
    


    _(下划线)分隔符

    当你要写一个很长的数字的时候:

    let x = 233333333
    

    数字太长会导致可读性很差。使用了数字分隔符_(下划线),就可以让数字读的更清晰:

    let x = 2_3333_3333
    // x 的值等同于 233333333,只是这样可读性更强,不用一位一位数了
    


    Intl.ListFormat

    Intl.ListFormat 是一个构造函数,用来处理和多语言相关的对象格式化操作。来通过一个例子了解一下。

    const list = ['Apple', 'Orange', 'Banana']
    new Intl.ListFormat('en-GB', { style: 'long', type: 'conjunction' }).format(list);
    // "Apple, Orange and Banana"
    new Intl.ListFormat('zh-cn', { style: 'short', type: 'conjunction' }).format(list);
    // 会根据语言来返回相应的格式化操作
    // "Apple、Orange和Banana"
    


    Intl.DateTimeFormat API 中的 dateStyle 和 timeStyle 的配置项

    Intl.ListFormat是一个用来处理多语言下的时间日期格式化的函数。ES2021 中给这个函数添加了两个新的参数:dateStyletimeStyledateStyletimeStyle选项可用于请求给定长度的,特定于语言环境的日期和时间。下面我们来通过例子来看一下这两个参数的用法:

    let a = new Intl.DateTimeFormat("en" , {
      timeStyle: "short"
    });
    console.log('a = ', a.format(Date.now())); // "13:31"
    let b = new Intl.DateTimeFormat("en" , {
      dateStyle: "short"
    });
    console.log('b = ', b.format(Date.now())); // "21.03.2012"
    // 可以通过同时传入 timeStyle 和 dateStyle 这两个参数来获取更完整的格式化时间的字符串
    let c = new Intl.DateTimeFormat("en" , {
      timeStyle: "medium",
      dateStyle: "short"
    });
    console.log('c = ', c.format(Date.now())); // "21.03.2012, 13:31"
    

    timeStyledateStyle配置项有三个(下面以timeStyle为例):

    • short:11:27 PM
    • medium:11:27:57 PM
    • long:11:27:57 PM GMT+11