ES2021 新特性
ES2021 (ES12)新特性:
1.String.prototype.replaceAll
2.Promise.any
3.WeakRefs
4.逻辑运算符和赋值表达式
5.数字分隔符号
String.prototype.replaceAll(searchValue, replaceValue)
replace只能替换第一个匹配的,如果需要匹配所有,需要使用正则加上全局标识g
const str = "1122334411"; str.replace("1", "@") //@122334411 str.replace(/1/, "@") //@122334411 str.replace(/1/g, "@") //@@223344@@
replaceAll可以直接替换全部匹配字符,如果用的是正则要加上g,不然会报错
str.replaceAll("1", "@") //@@223344@@
str.replaceAll(/1/, "@") //Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument
str.replaceAll(/1/g, "@") //@@223344@@
Promise.any()
接收一个Promise可迭代对象,只要其中的一个promise成功,就返回那个已经成功的promise,如果没有一个promise成功,则返回一个失败的Promise
如果传入的参数是一个空的迭代对象,则会返回一个已失败状态的Promise
如果传入的参数不包含任何promise,则返回一个异步完成的promise
该方法会返回第一个成功的 promise 。只要有一个 promise 成功此方法就会终止,它不会等待其他的 promise 全部完成。
Promise.any([ Promise.reject('rejected1'), Promise.reject('rejected2') ]) .then(res => { console.log(res) }) .catch(err => { console.error(err) // AggregateError: All promises were rejected }) Promise.any([ Promise.resolve('resolve1'), Promise.resolve('resolve2') ]) .then(res => { console.log(res) // resolve1 }) .catch(err => { console.error(err) })
WeakRefs
使用WeakRefs的Class类创建对对象的弱引用(对对象的弱引用是指当该对象应该被GC回收时不会阻止GC的回收行为)
当我们通过(const、let、var)创建一个变量时,垃圾收集器GC将永远不会从内存中删除该变量,只要它的引用仍然存在可访问。
WeakRef实例不会阻止 GC 回收,但是 GC 会在两次 EventLoop 之间回收 WeakRef实例。GC 回收后的 WeakRef 实例的 deref() 方法将会返回 undefined。
WeakRefs在很多情况下都很有用,比如使用Map对象来实现具有很多需要大量内存的键值缓存,在这种情况下最方便的就是尽快释放键值对占用的内存。
let obj = { name: 'Lazy' }
const ref = new WeakRef(obj);
let obj1 = ref.deref();
if (obj1) {
console.log(obj.name); // Lazy
}
逻辑赋值运算符(Logical Assignment Operators)
And and equals 运算符 (&&=)
let a = 1; let b = 2; a &&= b; console.log(a); // 2 // 等价于 if (a) { a = b; } console.log(a); // 2
Or or equals (||=)
let a = undefined; let b = 2; a ||= b; console.log(a); // 2 // 等价于 if (!a) { a = b; }
Question question equals (??=)
let a = undefined; let b = 2; a ??= b; console.log(a); // 2 // 等价于 if (a === null || a === undefined) { a = b; };
数字分隔符(Numeric Separators)
下划线“_”最为数字分隔符,但是分隔符不能在最前面,也不能在最后面
let a = 123123123123 //123123123123 let b = 123_123123_123 //123123123123 a===b //true a = _123123123123 //Uncaught ReferenceError: _123_123123_123 is not defined a = 123_123123_123_ //Uncaught SyntaxError: Numeric separators are not allowed at the end of numeric literals

浙公网安备 33010602011771号