ES11(2020)新特性:String 的 matchAll 方法、动态导入语句 import()等

更新日期: 2021-04-13阅读: 1.1k标签: match

Ecma标准定义了ECMAScript 2020语言。它是ECMAScript语言规范的第11版。自从1997年第一版出版以来,ECMAScript已经发展成为世界上使用最广泛的通用编程语言之一。它被称为嵌入在web浏览器中的语言,但也被广泛应用于服务器和嵌入式应用程序。

那么ES11又引入了那些新特性呢?

1. String 的 matchAll 方法
2. 动态导入语句 import()
3. import.meta
4. export * as ns from 'module'
5. Promise.allSettled
6. 新增数据类型: BigInt
7. 顶层对象: globalThis
8. 空值合并运算符: ??
9. 可选链操作符:?.


一、matchAll

matchAll() 方法返回一个包含所有匹配正则表达式的结果的迭代器。可以使用 for...of 遍历,或者使用 展开运算符(...) 或者 Array.from 转换为数组.

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';

const matchs = str.matchAll(regexp);
console.log(matchs); // RegExpStringIterator {}
console.log([...matchs])
/*
0: (4) ["test1", "e", "st1", "1", index: 0, input: "test1test2", groups: undefined]
1: (4) ["test2", "e", "st2", "2", index: 5, input: "test1test2", groups: undefined]
length: 2
/*

RegExp.exec()  和 matchAll() 区别:

在 matchAll 出现之前,通过在循环中调用 regexp.exec() 来获取所有匹配项信息。

const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
let match;

while ((match = regexp.exec(str)) !== null) {
  console.log(`Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`);
}
// expected output: "Found football start=6 end=14."
// expected output: "Found foosball start=16 end=24."

如果使用 matchAll ,就可以不必使用 while 循环加 exec 方式

const regexp = RegExp('foo[a-z]*','g');
const str = 'table football, foosball';
const matches = str.matchAll(regexp);

for (const match of matches) {
  console.log(`Found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`);
}
// expected output: "Found football start=6 end=14."
// expected output: "Found foosball start=16 end=24."

二、import()

import 标准的用法是导入的木块是静态的,会使所有被带入的模块在加载时就别编译,无法做到按需加载编译,降低了首页的加载速度。在某些场景中,你可能希望根据条件导入模块,或者按需导入模块,这是就可以使用动态导入代替静态导入了

在import() 之前,我们需要更具条件导入模块时只能使用 require() 

if (xx) {
  const module = require('/module')  
}

// 现在可以这么写
if (xx) {
  const module = import('/module')
}

@babel/preset-env 已经包含了 @babel/plugin-syntax-dynamic-import,因此如果要使用 import() 语法,只需要配置 @babel/preset-env 即可。

另外:import() 返回的是一个Promise 对象:

// module.js
export default {
  name: 'shenjp'
}

// index.js
if (true) {
  let module = import('./module.js');
  console.log(module); // Promise {<pending>
  module.then(data => console.log(data)); // Module {default: {name: "shenjp"}, __esModule: true, Symbol(Symbol.toStringTag): "Module"}
}

三、import.meta

import.meta对象是由ECMAScript实现的,它带有一个null的原型对象。这个对象可以扩展,并且它的属性都是可写,可配置和可枚举的。

<script type="module" src="my-module.mjs"></script>
console.log(import.meta); // { url: "file:///home/user/my-module.mjs" }

因为 import.meta 必须要在模块内部使用,如果不加 type="module",控制台会报错:Cannot use 'import.meta' outside a module。

在项目中需要下载 @open-wc/webpack-import-meta-loader  才能正常使用。

module: {
    rules: [
        {
            test: /\.js$/,
            use: [
                require.resolve('@open-wc/webpack-import-meta-loader'),
                {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            "@babel/preset-env",
                            "@babel/preset-react"
                        ]
                    },
                }
            ]
        }
    ]
}

效果如下:

//src/index.js
import React from 'react';
console.log(import.meta);//{index.js:38 {url: "http://127.0.0.1:3000/src/index.js"}}


四、export * as ns from 'module'

ES2020新增了 export * as XX from 'module',和 import * as XX from 'module'

// module.js
export * as ns from './info.js'

可以理解为下面两条语句的合并:

import * as ns from './info.js';
export { ns };

需要注意的是:export * as ns from 'module' 并不会真的导入模块,因此在该模块中无法使用 ns。


五、Promise.allSettled

Promise.allSettled()方法返回一个在所有给定的promise都已经fulfilled或rejected后的promise,并带有一个对象数组,每个对象表示对应的promise结果。

当您有多个彼此不依赖的异步任务成功完成时,或者您总是想知道每个promise的结果时,通常使用它。

想比较之下, Promise.all() 更适合做相互依赖的Promise,只要有一个失败就结束

const promise1 = Promise.resolve(100);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'info'));
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 200, 'name'))

Promise.allSettled([promise1, promise2, promise3]).
    then((results) => console.log(result));
/* 
    [
        { status: 'fulfilled', value: 100 },
        { status: 'rejected', reason: 'info' },
        { status: 'fulfilled', value: 'name' }
    ]
*/

可以看出,Promise.allSettled() 成功之后返回的也是一个数组,但是改数组的每一项都是一个对象,每个对象都有一个status属性,值为 fulfilled 和 rejected .

如果status是 fulfilled,那么改对象的另一个属性是 value ,对应的是该Promise成功后的结果。

如果status是 rejected,那么对象的另一个属性是 reason,对应的是该Promise失败的原因。


六、BigInt

BigInt 是一种数字类型的数据,它可以表示任意精度格式的整数。在此之前,JS 中安全的最大数字是 9009199254740991,即2^53-1,在控制台中输入 Number.MAX_SAFE_INTEGER 即可查看。超过这个值,JS 没有办法精确表示。另外,大于或等于2的1024次方的数值,JS 无法表示,会返回 Infinity。

BigInt 即解决了这两个问题。BigInt 只用来表示整数,没有位数的限制,任何位数的整数都可以精确表示。为了和 Number 类型进行区分,BigInt 类型的数据必须添加后缀 n.

//Number类型在超过9009199254740991后,计算结果即出现问题
const num1 = 90091992547409910;
console.log(num1 + 1); //90091992547409900

//BigInt 计算结果正确
const num2 = 90091992547409910n;
console.log(num2 + 1n); //90091992547409911n

我们还可以使用 BigInt 对象来初始化 BigInt 实例:

console.log(BigInt(999)); // 999n 注意:没有 new 关键字!!!

需要说明的是,BigInt 和 Number 是两种数据类型,不能直接进行四则运算,不过可以进行比较操作。

console.log(99n == 99); //true
console.log(99n === 99); //false 
console.log(99n + 1);//TypeError: Cannot mix BigInt and other types, use explicit conversionss


七、GlobalThis

JS 中存在一个顶层对象,但是,顶层对象在各种实现里是不统一的。

从不同的 JavaScript 环境中获取全局对象需要不同的语句。在 Web 中,可以通过 window、self 取到全局对象,但是在 Web Workers 中,只有 self 可以。在 Node.js 中,它们都无法获取,必须使用 global。

var getGlobal = function () {
    if (typeof self !== 'undefined') { return self; }
    if (typeof window !== 'undefined') { return window; }
    if (typeof global !== 'undefined') { return global; }
    throw new Error('unable to locate global object');
};

ES2020 中引入 globalThis 作为顶层对象,在任何环境下,都可以简单的通过 globalThis 拿到顶层对象。


八、空值合并运算符

ES2020 新增了一个运算符 ??。当左侧的操作数为 null 或者 undefined时,返回其右侧操作数,否则返回左侧操作数。

在之前我们经常会使用 || 操作符,但是使用 || 操作符,当左侧的操作数为 0 、 null、 undefined、 NaN、 false、 '' 时,都会使用右侧的操作数。如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。

?? 操作符可以规避以上问题,它只有在左操作数是 null 或者是 undefined 时,才会返回右侧操作数。

const someValue = 0;
const defaultValue = 100;
let value = someValue ?? defaultValue; // someValue 为 0 ,value 的值是 0


九、可选链操作符

可选链操作符 ?. 允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish, 即 null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。

例如,我们要访问 info 对象的 animal 的 reptile 的 tortoise。但是我们不确定 animal, reptile 是否存在,因此我们需要这样写:

const tortoise = info.animal && info.animal.reptile && info.animal.reptile.tortoise;

因为 null.reptile 或  undefined.reptile 会抛出错误:TypeError: Cannot read property 'reptile' of undefined 或 TypeError: Cannot read property 'reptile' of null,为了避免报错,如果我们需要访问的属性更深,那么这个这句代码会越来越长。

有了可选链之后我们就可以简化:

const tortoise = info.animal?.reptile?.tortoise;

可以看到可选链操作符 ?. 和空位合并操作符一样,都是针对的 null 和 undefined 这两个值。


链接: https://www.fly63.com/article/detial/10198

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!