ES2021新特性

一、 String.prototype.replaceAll

等价于replace正则中的全局匹配g

'hello world'.replace(/o/g, '_'); // hell_ w_rld

'hello world'.replaceAll('o', '_'); // hell_ w_rld

二、 数字分割符(_)

数字中间可以添加一个‘_’增加可读性,末尾和开头不能使用,不能连续使用多个,但是可以在多处使用

Number(1__000) 无效
Number(100_00) 正确
Number(100_00_00) 正确
Number('1_1') // 只能是数字中间,字符串无效

const num = 1_1
num * 10 => 110

三、 逻辑运算符

添加三种运算符:??=、&&=、||=

let test = undefined // 或者null
test = test ?? 'defaultValue' // 表示的意思是当test的值为null或者undefined时,test值为defaultValue
test = test && 'defaultValue' // 
test = test || 'defaultValue'

新运算符
test ??= 'defaultValue'
test &&= 'defaultValue'
test ||= 'defaultValue'

四、 Promise.any

接收Promise数组作为参数,返回合成的Promise,只要给定的Promise中有一个成功, 那么就以这个结果作为返回值

const promises = [
    ajax('1.com').then(),
    ajax('2.com').then(),
    ajax('3.com').then()
]
async ....
try{
    const ret = await Promise.any(promises)
    console.log('ret',ret)
}
catch(error) {
    console.log('error',error)
}

你可能感兴趣的:(前端javascript)