ES6-ES11新语法之ES9

rest参数和扩展运算符:

    // rest 参数和 spread 扩展运算符在ES6中已经引入,不过ES6中只针对数组,在ES9中为对象提供了 rest 参数和 spread 扩展运算符
    function fn({ name, age, ...others }) {
      console.log(name) // 孙艺珍
      console.log(age) // 20
      console.log(others) // {sex: "女", video: ['假如爱有天意', '现在去见你']}
    }

    fn({
      name: '孙艺珍',
      age: 20,
      sex: '女',
      video: ['假如爱有天意', '现在去见你']
    })

    // 对象的合并
    let obj = { name: '吴小明' }
    let obj1 = { age: 18 }
    let obj2 = { sex: '男', occupation: '前端' }
    let newObj = { ...obj, ...obj1, ...obj2 }
    console.log(newObj) // {name: "吴小明", age: 18, sex: "男", occupation: "前端"}

正则扩展:

  1、命名捕获分组groups

    let str = '<a href="http:www.baidu.com">百度</a>'

    // 提取 url 和 标签文本
    const reg = /<a href="(.*)">(.*)<\/a>/

    const result = reg.exec(str)

    console.log(result) // ['<a href="http:www.baidu.com">百度</a>', 'http:www.baidu.com', '百度']
    console.log(result[1]) // http:www.baidu.com
    console.log(result[2]) // 百度
    console.log(result.groups) // undefined

    // 命名捕获分组
    let str1 = '<a href="http:www.baidu.com">百度</a>'

    const reg1 = /<a href="(?<url>.*)">(?<text>.*)<\/a>/

    const result1 = reg1.exec(str1)

    console.log(result1)
    console.log(result1.groups) // {url: "http:www.baidu.com", text: "百度"}

  2、正则断言:根据目标内容的前后关键的字符进行唯一性的识别

    let str = 'JS5211314你知道么555啦啦啦'

    const reg = /\d+(?=啦)/ // 正向断言,取“啦”字前面的数字
    const result = reg.exec(str)
    console.log(result)

    const reg1 = /(?<=么)\d+/ // 反向断言,取“么”字后面的数字
    const result1 = reg1.exec(str)
    console.log(result1)

  3、dotAll模式:s----表示 . 可以匹配任意字符

    // dot 是 . 的意思,在正则中可以匹配除换行符以外的任意单个字符
    let str = `
      <ul>
        <li>
          <a>肖生克的救赎</a>
          <p>上映日期:1994-01-01</p>
        </li>
        <li>
          <a>阿甘正传</a>
          <p>上映日期:1995-01-01</p>
        </li>
        <li>
          <a>阿甘正传</a>
          <p>上映日期:1995-01-01</p>
        </li>
      </ul>
    `
    const reg = /<li>\s+<a>(.*?)<\/a>\s+<p>(.*?)<\/p>/ // \s匹配单个的空格,这种写法如果结构较多 \s+ 会永无止境
    const result = reg.exec(str)
    console.log(result)

    // 提取 ul 标签中的内容
    const reg1 = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/sg // s表示换行符也可以用 . 匹配    g表示全局匹配
    let result1
    let data = []
    while (result1 = reg1.exec(str)) {
      data.push({ title: result1[1], time: result1[2] })
    }

    console.log(data) // [{title: "肖生克的救赎", time: "上映日期:1994-01-01"}, {title: "阿甘正传", time: "上映日期:1995-01-01"}]

Promise.prototype.finally():

    // Promise.prototype.finally() 避免同样的语句在then()和catch()中各写一次
    const p = new Promise((resolve, reject) => {
      // resolve('成功')
      reject('失败')
    })
    p.then(data => {
      console.log(data)
    }).catch(err => {
      console.error(err)
    }).finally(other => {
      console.log('不管怎样我都会执行')
    })

 

 

 

 

x

posted @ 2020-11-27 10:39  吴小明-  阅读(377)  评论(0编辑  收藏  举报