# 🚀ES9
📅 2023/7/18
# for await...of
// 定义一个创建 promise 的函数
async function createTimeoutPromise(val) {
return new Promise(resolve => {
setTimeout(() => {
resolve(val)
}, 1000)
})
}
function handle() {
const list = [
createTimeoutPromise(10),
createTimeoutPromise(20)
]
// 第一,使用 Promise.all 执行
Promise.all(list).then(res => console.log(res))
// 第二,使用 for await ... of 遍历执行
for await (const p of list) {
console.log(p)
}
}
# Promise.finally()
promise链式调用最后会执行的方法,避免在 promise 的 then() 和 catch() 处理器中重复编写代码。
# 正则表达式扩展
- dotAll 修饰符 s:普通的正则匹配,不能用 点 ‘.’ 匹配到所有任意单个字符,像- - -换行符、行分隔符、段分隔符等匹配不到, 加上修饰符s后,可以用点 ‘.’ 匹配到所有任意单个字符
const reg = /./
console.log(reg.test('5')) //true
console.log(reg.test('a')) //true
console.log(reg.test('\n')) //false
console.log(reg.test('\r')) //false
console.log(reg.test(' ')) //true
console.log(reg.test('\u{2028}')) // 行分隔符 false
console.log(reg.test('\u{2029}')) // 段分隔符 false
const reg2 = /./s //dotAll匹配
console.log(reg2.test('5')) //true
console.log(reg2.test('a')) //true
console.log(reg2.test('\n')) //true
console.log(reg2.test('\r')) //true
console.log(reg2.test(' ')) //true
console.log(reg2.test('\u{2028}')) //true
console.log(reg2.test('\u{2029}')) //true
- 具名组匹配:普通的正则匹配,获取匹配到的子字符串,需要根据数字索引获取,ES9新增了具名组匹配方法,可以给子串添加名称,通过名称获取匹配到的子串内容,更加方便:
// 普通匹配
const reg = /(\d{4})-(\d{2})-(\d{2})/
const str = '2023-07-18'
const res = reg.exec(str)
console.log(res) //["2023-07-18","2023","07","18"]
console.log(res[0]) //2023-07-18
console.log(res[1]) //2023
console.log(res[2]) //07
console.log(res[3]) //18
// 具名组匹配
const reg2 = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
const res2 = reg2.exec(str)
console.log(res2) //["2023-07-18","2023","07","18"]
const resGroups = res2.groups
// 解构赋值
const {year, month, day} = resGroups
console.log(year, month, day) //2023 07 18
- 断言
先行断言- - -匹配前面紧跟着某段内容的字符串
规则:匹配紧跟某内容的,前面的字符串:/字符串(?=内容)/
后行断言- - -匹配后面紧跟着某段内容的字符串
规则:匹配紧接着某内容的,后面的字符串:/(?<=内容)字符串/ ;匹配不紧接着某内容的,后面的字符串:/(?<!内容)字符串/
// 先行断言
const str = 'helloWorld'
const str2 = 'hello222World'
console.log(str.match(/hello(?=World)/)) //hello
console.log(str2.match(/hello(?=World)/)) //null
// 后行断言
console.log(str.match(/(?<=hello)World/)) //World
console.log(str2.match(/(?<=hello)World/)) //null
console.log(str.match(/(?<!hello)World/)) //null
console.log(str2.match(/(?<!hello)World/)) //World