ES9(ES2018)新特性整理

一、异步迭代(for-await-of
  • 支持在异步循环中遍历 Promise 或 AsyncIterable 对象(如数据库流、分页 API)。

    async function processAsyncData(asyncIterable) {
      for await (const data of asyncIterable) {
        console.log(data);
      }
    }
二、 Promise.prototype.finally()
  • 无论 Promise 成功或失败,都会执行的回调(类似 try/catch/finally)。

    fetch('https://api.example.com/data')
      .then(response => response.json())
      .catch(error => console.error(error))
      .finally(() => console.log('请求结束')); // 无论成功失败都会执行

典型用途

  • 关闭加载动画

  • 清理资源

三、Rest/Spread 属性(对象扩展)
  • 对象剩余参数(Rest):收集剩余属性到新对象。

  • 对象扩展(Spread):合并对象(浅拷贝)。

    // 对象剩余参数(Rest)
    const { x, y, ...rest } = { x: 1, y: 2, z: 3, a: 4 };
    console.log(rest); // { z: 3, a: 4 }
    
    // 对象扩展(Spread)
    const obj1 = { a: 1 };
    const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }

对比数组的 ...

  • ES6 已支持数组的 Rest/Spread,ES2018 扩展到对象。

四、正则表达式增强

(1)命名捕获组(Named Capture Groups)

  • 用 ?<name> 给正则匹配分组命名,提高可读性。

    const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
    const match = regex.exec('2023-10-05');
    console.log(match.groups.year);  // "2023"

(2)反向断言(Lookbehind Assertions)

  • (?<=...) 正向反向断言(匹配前面是某模式的内容)。

  • (?<!...) 负向反向断言(匹配前面不是某模式的内容)。

    // 匹配前面是 $ 的数字
    const priceRegex = /(?<=\$)\d+/;
    console.log(priceRegex.exec('$100')[0]); // "100"

(3)dotAll 模式(s 标志)

  • 让 . 匹配任意字符(包括换行符 \n)。

    const regex = /foo.bar/s;
    console.log(regex.test('foo\nbar')); // true(普通模式会返回 false)

(4)Unicode 属性转义(\p{...}

  • 按 Unicode 属性匹配字符(如匹配所有字母、标点符号等)。

    // 匹配所有字母
    const regex = /\p{L}+/u;
    console.log(regex.test('你好Hello')); // true
五、 JSON.stringify 改进
  • 修复了 JSON.stringify 对 Unicode 代理对(如 emoji)的处理问题。

    // 早期版本会返回损坏的 Unicode
    console.log(JSON.stringify('\uD83D\uDE00')); // ✅ 现在正确输出 ""😀""
六、模板字符串修正(修订规范)
  • 明确模板字符串中非法转义序列的处理(如 \unicode 会报错)。

    // 早期允许,ES2018 明确报错
    console.log(`\unicode`); // SyntaxError

 注:如有缺失,请联系作者或在下方评论,我尽量在第一时间补充上去!!! 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

某公司摸鱼前端

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值