1️⃣ String.prototype.matchAll
ES2020 增加了String.prototype.matchAll()方法,可以一次性取出所有匹配。不过,它返回的是一个遍历器(Iterator),而不是数组。
1. 由于string.matchAll()返回的是遍历器,所以可以用for...of循环取出。相对于返回数组,返回遍历器的好处在于,如果匹配结果是一个很大的数组,那么遍历器比较节省资源。2. 遍历器转为数组是非常简单的,使用...运算符和Array.from()方法就可以了。
let str = `<ul><li><a>肖生克的救赎</a><p>上映日期: 1994-09-10</p></li><li><a>阿甘正传</a><p>上映日期: 1994-07-06</p></li></ul>`;//声明正则const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/sg//调用方法const result = str.matchAll(reg);// for(let v of result){// console.log(v);// }const arr = [...result];console.log(arr);
1️⃣ 类的私有属性
为class加了私有属性。方法是在属性名之前,使用#表示。
1. #age 就是私有属性,只能在类的内部使用(this.#age)。如果在类的外部使用,就会报错。2. #x 就是私有属性,在Person类之外是读取不到这个属性的。由于井号#是属性名的一部分,使用时必须带有#一起使用,所以#x和x是两个不同的属性。
class Person {// 公有属性name;// 私有属性#age;constructor(name, age) {this.name = name;this.#age = age;}method() {console.log(this.#age);}}const c = new Person('chen', 25)console.log(c.method()); // 25console.log(c.name); // chenconsole.log(c.age); // undefinedconsole.log(c.#age); // Uncaught SyntaxError: Private field '#age' must be declared in an enclosing class
1️⃣ Promise.allSettled 和 Promise.all()
Promise.allSettled()方法接受一组 Promise 实例作为参数,包装成一个新的 Promise 实例。只有等到所有这些参数实例都返回结果,不管是fulfilled还是rejected,包装实例才会结束。该方法由 ES2020 引入。
1. 无论返回的结果是成功还是失败,最后都是一个成功的 Promise
Promise.all() 同 Promise.allSettled() 的使用方法一样,Promise.all() 只有所有请求都成功才为成功,有一个失败则为失败
const p1 = new Promise((resolve, reject) => {setTimeout(() => {resolve('p1')}, 1000);})const p2 = new Promise((resolve, reject) => {setTimeout(() => {resolve('p2')}, 1000);})const p3 = new Promise((resolve, reject) => {setTimeout(() => {// resolve('p3')reject('p3')}, 1000);})// 调用 allSettled 方法const result = Promise.allSettled([p1, p2, p3])console.log(result);
1️⃣ 可选链操作符
?.
function main(config) {const dbHost = config && config.db && config.db.host;console.log(dbHost);// 链式操作符const cacheHost = config?.cache?.host;console.log(cacheHost);}main({db: {host: '192.168.1.100',username: 'root'},cache: {host: '192.168.1.200',username: 'admin'}})
1️⃣ 动态 import 导入
// hello.jsexport function hello() {alert('Hello');}btn.onclick = function () {import('./hello.js').then(module => {// import('./hello.js') 返回值为 Promise 对象,成功的返回值为模块的暴露对象module.hello();});}
