ES11新特性(2020)

272 阅读4分钟
String.prototype.matchAll()

方法返回一个包含所有匹配正则表达式的结果的迭代器

str.matchAll(regexp)

  • regexp

    正则表达式对象。如果所传参数不是一个正则表达式对象,则会隐式地使用 new RegExp(obj) 将其转换为一个 RegExp 。

    RegExp必须是设置了全局模式g的形式,否则会抛出异常TypeError

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';
str.matchAll(regexp) //RegExpStringIterator{}

Array.from(str.matchAll(regexp)) 或者 ...str.matchAll(regexp)

/*
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
/* 
动态导入import()

es6推出的import只能做到静态导入,在页面刚解析的时候会加载所有资源,无法做到动态导入,在es11新推出了动态导入,它可以做到按需导入

import返回一个promise对象

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

import('/module').then(res=>console.log(res))
import.meta

是一个给JavaScript模块暴露特定上下文的元数据属性的对象。它包含了这个模块的信息,比如说这个模块的URL

<script type="module" src="my-module.mjs"></script>
console.log(import.meta)
// { url: "file:///home/user/my-module.mjs" }
export * as name from './module.js'

合并导出 可以理解为

export * as ns from './info.js'
//等于
import * as ns from './info.js';
export { ns };
Promise.allSettled()

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

Promise.allSettled(iterable);

参数

iterable

const promise1=Promise.resolve(1);
const promise2=Promise.reject(2);
const promise3=Promise.resolve(3);

Promise.allSettled([promise1,promise2,promise3]).then(res=>{console.log(res)})
/*
[
    {status:'fulfilled',value:1},
    {status:'rejected',reason:2},
    {status:'fulfilled',value:3}
]
*/

可以看出来 返回值为一个数组,数组里的每一项都有status属性表示当前的状态,且如果当前执行的promise为成功的状态失败,则第二个属性为reason,否则为value

BigInt

BigInt 是一种数字类型的数据,它可以表示任意精度格式的整数。在此之前,JS 中安全的最大数字是 9009199254740991,即2^53-1,在控制台中输入 Number.MAX_SAFE_INTEGER 即可查看。超过这个值,JS 没有办法精确表示。另外,大于或等于2的1024次方的数值,JS 无法表示,会返回 Infinity。BigInt 即解决了这两个问题。BigInt 只用来表示整数,没有位数的限制,任何位数的整数都可以精确表示。为了和 Number 类型进行区分,BigInt 类型的数据必须添加后缀 n.

const alsoHuge = BigInt(9007199254740991)
typeof alsiHuge //bigint
GlobalThis

globalThis 提供了一个标准的方式来获取不同环境下的全局 this  对象(也就是全局对象自身)。不像 window 或者 self 这些属性,它确保可以在有无窗口的各种环境下正常工作。所以,你可以安心的使用 globalThis,不必担心它的运行环境。为便于记忆,你只需要记住,全局作用域中的 this 就是 globalThis

你可以在任何时候通过globalThis去访问最外层的对象

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

空值合并运算符 ??

当左侧的值为null或者undefined时,执行右侧的代码

与||不同的是,||为当左侧被Boolean值转换为false(0 、 null、 undefined、 NaN、 false、 '')的时候执行右边的

null??123 //123
null||123 //123
''||123 //123
''??123 //''
false??123 //false
false||123 //123
可选链操作符 ?.

?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined

所以说当我们不明确.的左边为undefined或者Null的时候可以用?.来代替

let b;
b.a
/*Uncaught TypeError: Cannot read properties of undefined (reading 'a')*/
b?.a
//undefined

//相当于 b?b.a:b