ES7-ES10的新特性

ES7

1. 数组查找与元素是否存在

let arr = [0, 1, 2, 3, 4, 5, 6]
console.log(arr.includes(4))

 2. 乘方的新写法

// es7之前
console.log(Math.pow(2, 3))
// es7
console.log(2 ** 3)

 ES8

1. async, await 。await接收的是一个Promise对象,如果传入的不是Promise对象,会自动将他转为Promise对象。

async用途是保证内部的所有await方法顺序执行

    async function step1() {
       return new Promise(resolve => {
            setTimeout(function () {
                resolve("步骤1完成")
            }, 1000)
        })
    }
    async function step2() {
        return new Promise(resolve => {
            setTimeout(function () {
                resolve("步骤2完成")
            }, 1000)
        })
    }
    async function doAll() {
        console.log(await step1())
        console.log(await step2())
        console.log("全部完成")
    }
    doAll()
    

2. 字符串补白

padStart,padEnd

    for (let i = 1; i < 20; i++) {
        console.log(i.toString().padStart(2, "0"))
    }

3. 获取Object的数据描述符

const score = {
        "andy": 100,
        "jack": 95,
        "tom": 90
    }
    // 指定tom不能被遍历
    Object.defineProperty(score, "tom", {
        enumerable: false   // 是否可以被遍历
    })
    console.log(Object.getOwnPropertyDescriptors(score))

可以看出对象数据的描述符有三种。

ES9

1. 遍历异步操作集合,for await of

    function Gen(time) {
        return new Promise((resolve, reject) => {
            setTimeout(function () {
                resolve(time)
            },time)
        })
    }

    async function test() {
        let arr = [Gen(2000), Gen(500), Gen(1000)]
        for await (let f of arr) {
            console.log(Date.now(), f)
        }
    }
    test()
const obj = {
        count: 0,
        Gen(time) {
            return new Promise(resolve => {
                setTimeout(function () {
                    resolve({done: false, value: time})
                }, time)
            })
        },
        [Symbol.asyncIterator]() {
            let that = this
            return {
                next() {
                    that.count++
                    if (that.count < 4) {
                        return that.Gen(Math.random() * 1000)
                    } else {
                        return {done: true, value: ""}
                    }
                }
            }
        }
    }

    async function test() {
        for await (let item of obj) {
            console.log(Date.now(), item)
        }
    }
    test()

猜你喜欢

转载自www.cnblogs.com/czl0325/p/13371166.html