ES2020(ES11) 9个新特性,前端开发者都掌握了吗?

2020-10-1709:00:37WEB前端开发Comments2,354 views字数 5830阅读模式

ECMAScript 2020 是 ECMAScript 语言规范的第11版。自1997年出版第一版以来,ECMAScript 已发展成为世界上使用最广泛的通用编程语言之一。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

ES2020(ES11) 引入了以下新特性:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

  • StringmatchAll 方法
  • 动态导入语句 import()
  • import.meta
  • export * as ns from 'module'
  • Promise.allSettled
  • 一种新的数据类型:BigInt
  • GlobalThis
  • Nullish coalescing Operator
  • Optional Chaining

ES2020(ES11) 9个新特性,前端开发者都掌握了吗?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

matchAll

matchAll() 方法返回一个包含所有匹配正则表达式的结果的迭代器。使用 for...of 遍历或者使用 操作符 ... Array.from 将其转换成数组。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

const reg = /[0-3]/g;
const data = '2020'; 
console.log(data.matchAll(reg));//data.matchAll 的返回值是一个迭代器
console.log([...data.matchAll(reg)]);
/**
 * 0: ["2", index: 0, input: "2020", groups: undefined]
 * 1: ["0", index: 1, input: "2020", groups: undefined]
 * 2: ["2", index: 2, input: "2020", groups: undefined]
 * 3: ["0", index: 3, input: "2020", groups: undefined]
 */
复制代码

Dynamic import

标准用法的 import 导入的模块是静态的,会使所有被导入的模块,在加载时就被编译(无法做到按需编译,降低首页加载速度)。有些场景中,你可能希望根据条件导入模块或者按需导入模块,这时你可以使用动态导入代替静态导入。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

import() 之前,当我们需要根据条件导入模块时,不得不使用 require()文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

如:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

if(XXX) {
    const menu = require('./menu');
}
复制代码

如今可以替换为:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

if(XXX) {
    const menu = import('./menu');
}
复制代码

@babel/preset-env 已经包含了 @babel/plugin-syntax-dynamic-import,因此如果要使用 import() 语法,只需要配置 @babel/preset-env 即可。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

提示: 请不要滥用动态导入(只有在必要情况下采用)。静态框架能更好的初始化依赖,而且更有利于静态分析工具和 tree shaking 发挥作用。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

另外,import() 返回的是一个 promise 对象。例如:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

//menu.js
export default {
    menu: 'menu'
}
复制代码
//index.js
if(true) {
    let menu = import('./menu');
    console.log(menu); //Promise {<pending>
    menu.then(data => console.log(data));//Module {default: {menu: "menu"}, __esModule: true, Symbol(Symbol.toStringTag): "Module"}
} else {

}
复制代码

import.meta

import.meta 会返回一个对象,有一个 url 属性,返回当前模块的url路径,只能在模块内部使用。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

<script src='./main.js' type="module"></script>
复制代码
//main.js
console.log(import.meta); //{url: "http://localhost:8080/main.js"} PS:使用了 http-server 启动
复制代码

因为 import.meta 必须要在模块内部使用,如果不加 type="module",控制台会报错:Cannot use 'import.meta' outside a module文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

最开始测试时,我是在 React 的项目中测试的,仅配置了 @babel/preset-env@babel/preset-react 预设,使用 import.meta 时,会报错如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

ES2020(ES11) 9个新特性,前端开发者都掌握了吗?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

安装 @open-wc/webpack-import-meta-loader,修改 webpack 的配置,可以正常运行。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

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

效果如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

//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'文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

//menu.js
export * as ns from './info';
复制代码

可以理解为是将下面两条语句合并为一句:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

import * as ns from './info';
export { ns };
复制代码

不过需要注意的是 export * as ns from './info' 并不会真的将导入模块,因此在该模块(menu.js)中,我们是获取不到 ns 的。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

Promise.allSettled

Promise.all 或者 Promise.race 有的时候并不能满足我们的需求。比如,我们需要在所有的 promise 都结束的时候做一些操作,而并不在乎它们是成功还是失败。在没有 Promise.allSettled 之前,我们需要自己去写实现。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

Promise.allSettled() 方法返回一个在所有给定的 promise 都已经 fulfilledrejected 后的 promise ,并带有一个对象数组,每个对象表示对应的 promise 结果。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

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 属性,值为 fulfilledrejected,如果status 的值是 fulfilled,那么该对象还有一个 value 属性,其属性值是对应的 promise 成功的结果;如果 status 的值是 rejected,那么该对象有一个 reason 属性,其属性值是对应的 promise 失败的原因。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

BigInt

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

BigInt 即解决了这两个问题。BigInt 只用来表示整数,没有位数的限制,任何位数的整数都可以精确表示。为了和 Number 类型进行区分,BigInt 类型的数据必须添加后缀 n.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

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

//BigInt 计算结果正确
const num2 = 90091992547409910n;
console.log(num2 + 1n); //90091992547409911n
复制代码
//Number 类型不能表示大于 2 的 1024 次方的数值
let num3 = 9999;
for(let i = 0; i < 10; i++) {
    num3 = num3 * num3;
}
console.log(num3); //Infinity

//BigInt 类型可以表示任意位数的整数
let num4 = 9999n;
for(let i = 0n; i < 10n; i++) {
    num4 = num4 * num4;
}
console.log(num4); //一串超级长的数字,这里就不贴了
复制代码

我们还可以使用 BigInt 对象来初始化 BigInt 实例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

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

需要说明的是,BigIntNumber 是两种数据类型,不能直接进行四则运算,不过可以进行比较操作。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

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 中存在一个顶层对象,但是,顶层对象在各种实现里是不统一的。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

从不同的 JavaScript 环境中获取全局对象需要不同的语句。在 Web 中,可以通过 windowself 取到全局对象,但是在 Web Workers 中,只有 self 可以。在 Node.js 中,它们都无法获取,必须使用 global文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

globalThis 之前,我们这样去获取全局对象:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

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 拿到顶层对象。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

Nullish coalescing Operator

ES2020 新增了一个运算符 ??。当左侧的操作数为 null 或者 undefined时,返回其右侧操作数,否则返回左侧操作数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

使用 || 操作符,当左侧的操作数为 0nullundefinedNaNfalse'' 时,都会使用右侧的操作数。如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

例如:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

const defaultValue = 100;
let value = someValue || defaultValue;
//当 someValue 转成 boolean 值为 false 时,value 的值都是 defaultValue
复制代码

someValue 的值为 0 时 ,我们其实期望 value 值为 0, 但是它却被错误的分配成了 100.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

?? 操作符可以规避以上问题,它只有在左操作数是 null 或者是 undefined 时,才会返回右侧操作数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

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

Optional Chaining

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

例如,我们要访问 info 对象的 animalreptiletortoise。但是我们不确定 animal, reptile 是否存在,因此我们需要这样写:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

const tortoise = info.animal && info.animal.reptile && info.animal.reptile.tortoise;
复制代码

因为 null.reptileundefined.reptile 会抛出错误:TypeError: Cannot read property 'reptile' of undefinedTypeError: Cannot read property 'reptile' of null,为了避免报错,如果我们需要访问的属性更深,那么这个这句代码会越来越长。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

而有了可选链操作符 ?.,我们在访问 reptile 之前,不再需要校验 info.animal 的值。同样,在访问 info.animal.reptile.tortoise 之前,也不需要校验 info.animal.reptile 的值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

上面的代码简化为:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

const tortoise = info.animal?.reptile?.tortoise;
复制代码

JS在尝试访问 info.animal.reptile 之前,会隐式检查并确定 info.animal 的值不是 nullundefined,如果其值是 nullundefined,那么表达式短路计算直接返回 undefined文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

可以看到可选链操作符 ?. 和空位合并操作符一样,都是针对的 nullundefined 这两个值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

作者:刘小夕文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20387.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/20387.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定