JS_ES2021新增特性

features

  • String.prototype.replaceAll()
  • Promise.any
  • WeakRef
  • &&=, ||= and ??=
  • Numeric separators

String.prototype.replaceAll()

在此之前只能使用正则替换,现在可以直接使用一个快捷方式;replaceAll。

//前
'jxvxscript'.replace(/x/g, 'a');

//后
// jxvxscript becomes javascript
'jxvxscript'.replaceAll('x', 'a');

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);
});

WeakRefs

使用WeakRefs的Class类创建对对象的弱引用(对对象的弱引用是指当该对象应该被GC回收时不会阻止GC的回收行为)

Logical Assignment Operators

包括这些运算符:&&=, ||= ,??= ;

a = 1;
b = 2;
a&&=b // a=2

/*
以上代码相当于
a && a = b

??=
作用相当于
if(a == null || a==undefined){
	a=b
}
*/

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

猜你喜欢

转载自blog.csdn.net/weixin_44599931/article/details/120458192