ES2024
ES2024 主要补充了更方便的 Promise 构造方式、原生对象分组以及正则表达式的增强。
1. Promise.withResolvers()
允许创建一个新的 Promise,并同时暴露出它的 resolve 和 reject 函数。这在处理事件监听器或流式数据,需要将回调函数转换为 Promise(或实现可以取消的 Promise)时,能够极大减少代码嵌套。
// 以前的写法(闭包嵌套)
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
// ES2024 写法
const { promise, resolve, reject } = Promise.withResolvers();
2. Object.groupBy() & Map.groupBy()
原生实现了类似 Lodash 的 groupBy 功能,能够非常方便地对数组或可迭代对象进行分组。
Object.groupBy返回一个普通对象(没有原型)。Map.groupBy返回一个Map(允许键是对象类型)。
const inventory = [
{ name: 'asparagus', type: 'vegetables', quantity: 5 },
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'cherries', type: 'fruit', quantity: 5 },
{ name: 'fish', type: 'meat', quantity: 22 }
];
const result = Object.groupBy(inventory, ({ type }) => type);
/*
{
vegetables: [{ name: 'asparagus', type: 'vegetables', quantity: 5 }],
fruit: [
{ name: 'bananas', type: 'fruit', quantity: 0 },
{ name: 'cherries', type: 'fruit', quantity: 5 }
],
meat: [
{ name: 'goat', type: 'meat', quantity: 23 },
{ name: 'fish', type: 'meat', quantity: 22 }
]
}
*/
3. 正则表达式 v 标志 (Unicode Sets)
/v 标志是原有 /u 标志的升级版,增加了在字符类([])内部进行集合运算(交集、差集)的能力,也支持匹配多字符的字符串属性。
// 匹配所有属于希腊字母,但不是字母的字符(差集运算)
const regex = /[\p{Script_Extensions=Greek}--\p{Letter}]/v;
4. 字符串格式校验 (isWellFormed / toWellFormed)
用于检查和修复字符串中是否存在孤立的(非法的)代理对(Surrogate pair,通常由于错误处理 Unicode 引起)。这对处理来自外部系统的文本或 URI 编码时很有帮助。
5. ArrayBuffer 大小调整与转移
ArrayBuffer.prototype.resize():可以直接动态调整缓冲区大小,不用重新分配内存。ArrayBuffer.prototype.transfer():更高效地将缓冲区的控制权(内存)转移给另一个 ArrayBuffer,而无需深拷贝。