es2018

132 阅读1分钟
  1. 剩余(Rest) / 展开(Spread)运算符

    ES6 在处理数组解构时,引入了 rest(剩余)元素的概念,例如:

    const numbers = [1, 2, 3, 4, 5]
    [first, second, ...others] = numbers
    

    还有展开元素时

    const numbers = [1, 2, 3, 4, 5]
    const sum = (a, b, c, d, e) => a + b + c + d + e
    const sum = sum(...numbers)
    

    还有函数的剩余参数

    const numbers = [1, 2, 3, 4, 5]
    const sum = (a, ...rest) => rest
    const sum = sum(...numbers)
    

    ES2018 为对象引入了类似的功能。

    rest(剩余) 属性

    const { first, second, ...others } = { first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }
    first // 1
    second // 2
    others // { third: 3, fourth: 4, fifth: 5 }
    
  2. Asychronous Iteration

    新的 for-await-of 构造允许您使用异步可迭代对象作为循环迭代:

    function request () {
        return Promise.resolve({
            code: (Math.random() * 100).toFixed(0)
        })
    }
    async function* asyncGenerator() {
      yield await request();
      yield await request();
    }
    
    (async function() {
      for await (res of asyncGenerator()){
    		console.log(res)
    	}
    }());
    
  3. Promise.prototype.finally()

  4. 正则表达式, 先行断言(lookahead) 和 后行断言(lookbehind)

    lookahead ?=

    /Roger(?= is)/.test('Roger is my dog') // true,  匹配' is'前面的'Roger'
    'abcd'.replace(/(?=cd)/, ',') //ab,cd 匹配'cd'前面的位置, 注意是指那个空位置, 即'ab'和'cd'之间的位置
    

    ! lookahead ?!

    /a(?!b)/g.test('abcd') // false,  匹配所有不是'b'前面的位置
    

    lookbehind ?<=

    /(?<=is) my/.test('Roger is my dog') // true,  匹配'is'后面的' my'
    'abcd'.replace(/(?<=ab)/, ',') //ab,cd 匹配'ab'后面的位置, 注意是指那个空位置, 即'ab'和'cd'之间的位置
    

    ! lookbehind ?<!

    /(?<!b)c/g.test('abcd') // false,  匹配所有不是'b'后面的位置
    
  5. Uicode属性转译 \p{}\P{}

    不懂, 看了也不懂, 忽略吧

  6. 命名捕获组

    在 ES2018 中,可以为捕获组分配一个名称,而不是仅在结果数组中分配一个 slot(插槽)

    const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
    const result = re.exec('2015-01-02')
     
    // result.groups.year === '2015';
    // result.groups.month === '01';
    // result.groups.day === '02';
    
  7. 正则表达式 s 的标志

    s 标志是 single line (单行)的缩写,它使 . 匹配新的行字符。如果没有它,点将匹配普通字符,而不是新行:

    /hi.welcome/.test('hi\nwelcome') // false
    /hi.welcome/s.test('hi\nwelcome') // true