ES7~ES11 finishing

Table of contents

1. ES7

1.1、includes()

1.2, ** exponent operator

2. ES8

2.1. async function + await expression

2.2. Object method extension

3. ES9

3.1, rest parameters, expansion operators

3.2. Regular expansion

3.2.1. Named capture grouping (there is a problem with the a tag)

3.2.2. Forward assertion and reverse assertion

3.2.3. dotAll mode

4. ES10

4.1. Object.fromEntries() converts a two-dimensional array into an object

4.2. String extension methods trimStart() and trimEnd()

4.3. Array extension methods flat and flatMap

5. ES11

5.1, Promise.allSettled() method

5.2. String String.prototype.matchAll()

5.3. Optional chain operator?.

1. ES7

1.1、includes()

includes: Determines whether an array/string contains an element and returns a Boolean value

eg: const Isweeday = ['Monday', 'Tuesday', 'Wednesday', 'Thursday'];

console.log(Isweeday.includes('Tuesday'), 'Judgment', Isweeday.includes('Sunday'));//true 'Judgment' false

1.2, ** exponent operator

**: Exponential operator, implements power operation, equivalent to Math.pow()

eg: console.log(2 ** 10, 'Same', Math.pow(2, 10));//1024 'Same' 1024

2. ES8

2.1. async function + await expression

   // 创建promise对象
    const p = new Promise((resolve, reject) => {
        // resolve("用户数据");
        reject("失败了");
    })
    // await表达式 要放在async函数中,一旦失败借助try{...}catch{...}捕获异常
    async function main() {
        try {
            let result = await p;
            console.log(result, '成功');//resolve==> 成功
        } catch (e) {
            console.log(e, '失败');//reject==> 失败
        }
    }
    // 调用函数
    main()

(Practical application: sending a request)

The one on the left is in the form of promise, and the one on the right is in the form of async+await (you can receive multiple at one time)

2.2. Object method extension

    let obj={
        name:'小花',
        year:['2001','2002','2003'],
        class:'九年级一班'
    }
    // 获取对象所有的键
    console.log(Object.keys(obj));//['name', 'year', 'class']
    console.log(Object.values(obj));//获取对象所有的值
    // 将对象的键和值整合为数组
    console.log(Object.entries(obj));//['name', '小花']...
    // 创建Map
    const m=new Map(Object.entries(obj))
    console.log(m.get('class'));//九年级一班

3. ES9

3.1, rest parameters, expansion operators

    function connect({ host, port, ...user }) {
        console.log(host, port, user);//127.0.0.1 3306 {username: 'root', password: 'root123'}
    }
    connect({
        host: '127.0.0.1',
        port: '3306',
        username: 'root',
        password: 'root123'
    })
    let obj1 = {
        name: 'dan'
    }
    let obj2 = {
        age: '18'
    }
    const total = { ...obj1, ...obj2 }
    console.log(total);//{name: 'dan', age: '18'}

3.2. Regular expansion

3.2.1. Named capture grouping (there is a problem with the a tag)

    let str = "<h1>标题</h1>"
    const reg1 = /<h1>(.*)<\/h1>/;
    const reg2 = /<h1>(?<text>.*)<\/h1>/;
    const result = reg2.exec(str)
    console.log("result", result);
// ["<h1>标题</h1>", "标题", { groups: { text: '标题' } }]
    let str1 = "href='http://www.baidu.com'"
    const reg = /href='(.*)'/;
// http://www.baidu.com

3.2.2. Forward assertion and reverse assertion

Meaning: Find relevant content based on specified information


    let strVal = 'QAZEDC2354你看这里5555啦啦啦'
    // const reg = /\d+(?=啦)/;//正向断言
    const reg = /(?<=里)\d+/;//反向断言
    console.log(reg.exec(strVal));['5555']

3.2.3. dotAll mode

Generally, for data whose content is html elements, if you want to get the text content inside, you can use it.

matchAll in ES11 can also achieve the following effects.

    let strHtml = `
    <ul>
        <li>
            <h1>救赎</h1>
            <p>上映日期:11月</p>
        </li>
        <li>
            <h1>晚安</h1>
            <p>上映日期:2月</p>
        </li>
    </ul>`
    // const reg = /<li>\s+<h1>(.*?)<\/h1>\s+<p>(.*?)<\/p>/;//非dotAll模式
    const reg = /<li>.*?<h1>(.*?)<\/h1>.*?<p>(.*?)<\/p>/gs;//dotAll模式,加上g,可以拿到所有
    let result;
    let data = []
    while (result = reg.exec(strHtml)) {
        data.push({ title: result[1], time: result[2] })
    }
    console.log(reg.exec(strHtml), data);

4. ES10

4.1. Object.fromEntries() converts a two-dimensional array into an object

const result = Object.fromEntries([
  ['name', 'lisa'],
  ['subject', 'Java,html,c++']
])
console.log(result);//{name: 'lisa', subject: 'Java,html,c++'}

 ES8 Object.entries() converts the object into a two-dimensional array. These two operations can be said to be inverse operations.

const result = Object.entries({ name: 'lisa', subject: 'Java,html,c++' })
console.log(result);

 

4.2. String extension methods trimStart() and trimEnd()

There is trim() in ES5, which removes all spaces. These two are to remove the leading and following spaces.

    let str='   Iloveyou   '

    console.log(str);

    console.log(str.trimStart());

    console.log(str.trimEnd());

4.3. Array extension methods flat and flatMap

flat(n): Convert multi-dimensional array to low-bit array, n is depth

    const arr = [1, 2, 3, [5, 6, 7]]
    console.log(arr.flat());// [1, 2, 3, 5, 6, 7]
    // 三维数组转一维数组 ,深度为2
    const arr2 = [2, 4, 6, [1, 3, [8, 9], 5]]
    console.log(arr2.flat(2));// [2, 4, 6, 1, 3, 8, 9, 5]

flatMap(): Convert the array in the loop into a low-bit array

    const brr = [9, 8, 7].flatMap(item => [item * 10])
    console.log(brr);// [90, 80, 70](flatMap)   [[90],[80],[70]](map)

5. ES11

5.1, Promise.allSettled() method

In the case of multiple promises asynchronously, if you want to get all the results, you can use all or allSettled.

However, the former will report an error once an asynchronous error occurs, while the latter can get any possible result.

  const p1 = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('数据---1')
        }, 1000);
    })
    const p2 = new Promise((resolve, reject) => {
        setTimeout(() => {
            // resolve('数据---2')
            reject('数据---2')
        }, 1000);
    })
    const result = Promise.all([p1, p2]);
    const result2 = Promise.allSettled([p1, p2]);
    console.log(result,result2);

5.2. String String.prototype.matchAll()

Quickly extract HTML text content, combined with looping, has the same effect as ES9's dotAll mode.

    let strHtml = `
    <ul>
        <li>
            <h1>救赎</h1>
            <p>上映日期:11月</p>
        </li>
        <li>
            <h1>晚安</h1>
            <p>上映日期:2月</p>
        </li>
    </ul>`;
    const reg = /<li>.*?<h1>(.*?)<\/h1>.*?<p>(.*?)<\/p>/gs
    const result = strHtml.matchAll(reg)
    // for (let v of result) {
    //     console.log(v);
    // }
    const arr = [...result]
    console.log(arr);

5.3. Optional chain operator?.

?.Find the corresponding attribute value faster than the object's properties.

  function main(config) {
        // const dbHost = config && config.db && config.db.host;
        const dbHost = config?.db?.host;//可选链操作符
        console.log(dbHost);//120.0.0.1
    }
    main({
        db: {
            host: '120.0.0.1',
            username: 'root'
        }
    })

Guess you like

Origin blog.csdn.net/qq_44930306/article/details/131637311