0
点赞
收藏
分享

微信扫一扫

ES9新特性

心存浪漫 2023-06-20 阅读 93

ES9新特性

1、对象的剩余参数与扩展运算符

//剩余参数
let obj = {
    name: "twj",
    age: 100,
    location: "changsha"
}
let { name, ...other } = obj
console.log(name, other) //{age: 100, location: 'changsha'}
function test(name, ...other) {
    console.log(name, other) //{name: 'twj', age: 100, location: 'changsha'}
}
test(obj)
//...扩展运算符
let obj1 = {
    name: "twj",
    location: "changsha"
}
let obj2 = {
    name: "xiaoming",
    age: 100
}
let obj3 = { ...obj1, ...obj2 } //后来者居上
console.log(obj3) //{name: 'xiaoming', location: 'changsha', age: 100}
//浅拷贝
let obj5 = {
    name: "twj",
    age: 200
}
let obj6 = { ...obj5 }
console.log(obj6) //{name: 'twj', age: 200}

2、正则表达式命名捕获组

let str = "今天是2023-04-12"
let reg = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/
let { year, month, day } = reg.exec(str).groups
console.log(year, month, day) //2023 04 12

3、Promise.finally()

function ajax() {
    return new Promise((resolve, reject) => {
        resolve("data-111")
    })
}
//显示loading
ajax().then(data => {
    console.log(data)
}).catch(err => {
    console.log(err)
}).finally(() => {
    console.log("finally")
    //finally不管成功还是失败都会执行
    //这里做一些隐藏loading,关闭缓存,关闭对话框等等
})

4、异步遍历器

function timer(t) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve("data-" + t)
        }, t)
    })
}
//实际开发中,可以把timer替换成真实的异步任务,实现js的任务调度功能
async function* gen() {
    yield timer(1000)
    yield timer(2000)
    yield timer(3000)
}
async function test() {
    let g = gen()
    let arr = [g.next(), g.next(), g.next()]
    //for await里面循环的是异步遍历器生成的对象,将异步任务按照串联的形式执行
    for await (let item of arr) {
        console.log("start-", Date.now())
        console.log(item)
        console.log("end-", Date.now())
    }
}
test()

上一篇文章下一篇文章
ES8新特性ES10新特性
举报

相关推荐

0 条评论