ES2021(ES12)新特性在最新版Google已支持,不得不说Google牛逼
关键词: ES2021、ES12、new feature
摘要:ES2021(ES12)处于流程的第4阶段。ES12已于2021年6月发布,我们来看看计划发布的新功能。
目录features:
- String.prototype.replaceAll()
- Promise.any
- WeakRef
- &&=、||= 、??=
- Numeric separators
1、String.prototype.replaceAll()
在此之前只能使用正则替换,现在可以直接使用一个快捷方式:replaceAll。
//前
'jxvxscript'.replace(/x/g, 'a');
//后
'jxvxscript'.replaceAll('x', 'a');
// jxvxscript => javascript
2、Promise.any
Promise.any() 接收一个Promise可迭代对象的数组,只要其中的一个 promise 成功,就返回那个已经成功的 promise 。 如果可迭代对象中没有一个 promise 成功(即所有的 promises 都失败/拒绝),就返回一个失败的 promise。
const promise1 = new Promise((resolve, reject) => reject('我是失败的Promise_1'));
const promise2 = new Promise((resolve, reject) => reject('我是失败的Promise_2'));
const promiseList = [promise1, promise2];
Promise.any(promiseList).then(values=>{
console.log(values);
})
.catch(e=>{
console.log(e);
});
3、WeakRefs
使用WeakRefs的Class类创建对对象的弱引用(对对象的弱引用是指当该对象应该被GC回收时不会阻止GC的回收行为)
4、Logical Assignment Operators(逻辑赋值运算符)
包括这些运算符:&&=, ||= ,??=
a = 1;
b = 2;
a&&=b // a=2
/*
以上代码相当于
a && a = b
??=
作用相当于
if(a == null || a==undefined){
a=b
}
*/
5、Numeric Separators ( 数字分隔符)
// previous syntax before ES12
const number = 92145723;
// new syntax coming with ES12
const number = 92_145_723;
console.log(number) // 92145723
//对国人来说可以这样,万,亿为单位
const number = 1_0000;
console.log(number) // 10000