ECMAScript 2020/ES2020/ES11 于 6 月发布,并且已经在现代浏览器中实现。
一、空值合并
只针对 null 和 undefined,对 '' 、 0 、 NaN 及 false 无效,所以这同 || 是有区别的,写法是 ?? 连接
示例:
const user = { age: 0 }
let age = user.age ?? 50 // value is 0
let ageWrong = user.age || 50 // value is 50
仅当 age 为 undefined 或者 null 时才使用 50 这个值。
二、可选链
在对象属前面使用 ?. 连接会检查该属性是否为 null 或 undefined,以避免代码崩溃。
示例:
以前的写法
const house = { owner: { name: 'Jim', pet: null }};
if(house && house.owner && house.owner.pet && house.owner.pet.type === 'dog'){
console.log('owner has a dog');
}
新特性写法
if (house?.owner?.pet?.type === 'dog') {
console.log('owner has a dog');
}
三、Promise.allSettled
以前处理多个异步请求一并返回使用的是 Promise.all 但如果其他一个请求失败了就会报出异常,但使用 Promise.allSettled则不一样,不管请求成功或失败都会把结果返回过来
示例:
const promises = [Promise.resolve(1), Promise.reject(2)];
const [result1, result2] = await Promise.allSettled(promises);
即使其他 promise 被拒绝了,我们仍然可以在这里使用 result1 的值。
四、matchAll
如果要用正则表达式查找所有的匹配项,可以用 match 来得到所有子字符串。但是,如果你既需要子字符串又需要索引,该怎么办?这时可以用 matchAll 并进行重复匹配。
示例:
const matches = 'Here are some numbers: 3 15 32'.matchAll(/\d+/g);
for (const match of matches) {
console.log(match);
}
// 输出:
// ["3", index: 22, input: "Here are some numbers: 3 15 32", groups: undefined]
// ["15", index: 24, input: "Here are some numbers: 3 15 32", groups: undefined]
// ["32", index: 27, input: "Here are some numbers: 3 15 32", groups: undefined]
五、BigInt
在处理大于 9007199254740991 的数字时应该用 BigInt。 BigInt 在数字末尾用 n 表示。
示例:
9_007_199_254_740_991 + 2; // 9007199254740992
BigInt(9_007_199_254_740_991) + BigInt(2) // 9007199254740993n
六、动态导入
以前是先导入再使用,新特性可以动态导入使用了,因为 import() 会与模块一起返回一个 Promise
示例:
const utils = await import('utils');
七、globalThis
如果你的代码需要在多个环境(例如浏览器和 Node 服务器)下运行,那么它们所使用全局对象名称并不一致。在浏览器中用的是 window,Node 则用的是 global,而 web worker 用的是 self 。现在,无论代码在哪种环境中运行,globalThis 都能够为你提供正确的全局对象。
示例:
if (typeof globalThis.alert === 'function'){
globalThis.alert('hello');
}