ES9(ES2018)新属性

文章类型:Javascript

发布者:hp

发布时间:2025-03-06

一:属性

1:异步迭代 (Async Iteration):通过 for await...of 循环迭代异步数据源。

async function processPromises(promises) {  
  for await (const result of promises) {  
    console.log(result);  
  }  
}  

2:对象的 rest/spread 属性:扩展对象属性的拷贝和合并能力,支持对象结构时提取剩余属性,或者展开属性

const obj = { a: 1, b: 2, c: 3 };  
const { a, ...rest } = obj;  
console.log(rest); // { b: 2, c: 3 }  

const merged = { ...obj, d: 4 }; // { a:1, b:2, c:3, d:4 }  

3:Promise.finally():为Promise添加 finally 方法。无论成功还是失败都会执行

fetch("/data")  
  .then(res => res.json())  
  .catch(err => console.error(err))  
  .finally(() => {  
    console.log("请求结束");  
  });  

4:正则表达式的新增特性:包括s修饰符、命名捕获组、反向断言和dotAll模式。

命名捕获组=>通过 ?<name> 语法为捕获组命名,通过 groups 属性访问结果‌

const regex = /(?<year>\d{4})-(?<month>\d{2})/;  
const match = regex.exec("2025-02");  
console.log(match.groups.year);  // "2025"  

反向断言=>支持 (?<=...)(肯定反向查找)和 (?<!...)(否定反向查找)‌

// 匹配以美元符号开头的数字  
const regex = /(?<=\$)\d+/;  
console.log(regex.exec("$100")); // "100"  

dotAll模式=>通过 s 修饰符使 . 匹配任意字符

const regex = /hello.world/s;  
console.log(regex.test("hello\nworld")); // true  

Unicode 属性转义=>通过 \p{Property} 语法匹配 Unicode 字符属性

const regex = /\p{Number}/u;  
console.log(regex.test("①")); // true  

5:模块字符串修正:允许嵌套未转义的模板字符串

6:JSON超集兼容:支持字符串中包含未转义的换行符和分隔符‌

二:总结

1:异步流控制‌:finally 统一处理异步操作的收尾逻辑(如关闭加载状态)‌5。

‌2:数据处理‌:对象展开与解构简化数据合并和提取‌5。

‌3:复杂文本解析‌:命名捕获组和反向断言提升正则表达式的精确度‌