7个ECMAScript 11的新特性,你需要了解一下

1、String.prototype.matchAll
// matchAll 用于字符串批量匹配正则, 返回一个 可迭代对象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);const arr = [...result];console.log(arr);
2、类的私有属性
class Person {// 公有属性name;// 私有属性constructor(name,age,weight) {this.name = name;this.this.}intro(){console.log(this.name);console.log(this.console.log(this.}}const boy = new Person('张三',22,'80kg');console.log(boy.name);// Uncaught SyntaxError: Private field '#age' must be declared in an enclosing class// console.log(boy.#age);// console.log(boy.#weight);boy.intro();
3、Promise.allSettled
// Promise.allSettled()不管参数中的promise是fulfilled还是rejected,都会等参数中的实例都返回结果,包装实例才会结束。// 声明两个promise对象const p1 = new Promise((resolve, reject) => {setTimeout(() => {resolve('商品数据 -1');}, 1000)});const p2 = new Promise((resolve, reject) => {setTimeout(() => {reject('出错啦');}, 1000)});// 调用 allSettled 方法const result = Promise.allSettled([p1,p2]);console.log(result);/*Promise {<pending>}__proto__: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: Array(2)0: {status: "fulfilled", value: "商品数据 -1"}1: {status: "rejected", reason: "出错啦"}length: 2__proto__: Array(0)*/
4、可选链操作符
// 项目中经常会遇到深层次嵌套属性的验证,我们所能做的就是通过&&每层依次验证,这样看起来代码很繁琐,但又不得不这样做。// 为了简化代码, 使用" ?. "可选链式操作符, 会自动检测 ? 前面的对象是否存; 存在 则调用 , 不存在 则为 undefinedfunction main(config){// const dbHost = config && config.db && config.db.host;const dbHost = config?.db?.host;console.log(dbHost); // 192.168.1.100}main({db:{host:'192.168.1.100',user:'root'},cache:{host:'192.168.1.200',user:'admin'}});
5、动态 import 导入
// 动态 import ,用于模块懒加载, 用到一个模块的时候再加载, 没用到就不加载// 使用 improt(路径) 方法, 返回一个promise 对象<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title></head><body><button id="btn">点击按钮</button></body><script>let btn = document.getElementById('btn');btn.onclick = function(){import('./34.ES11-动态import.js').then(module=>{console.log(module);module.hello();});}</script></html>// 34.ES11-动态import.jsexport function hello() {console.log('hello');}
6、bigInt
// 大整型let n = 123n;console.log(n, typeof (n)); // 123n "bigint"// 函数let n2 = 123;console.log(BigInt(n2)); // 123n// console.log(BigInt(1.2)); //报错// 大数值运算let max = Number.MAX_SAFE_INTEGER;console.log(max); // 9007199254740991console.log(max + 1); // 9007199254740992console.log(max + 2); // 9007199254740992console.log(BigInt(max)); //9007199254740991nconsole.log(BigInt(max) + 1n); // 9007199254740992nconsole.log(BigInt(max) + 2n); //9007199254740993n
7、 globalThis 对象
// global 是一个变量, 永远指向顶级对象// 在js中console.log(globalThis); // window// 在node中console.log(globalThis); // global
学习更多技能
 请点击下方公众号 

评论
