ES16(ES2025)新特性
发布时间:2025 年 6 月 26 日 ES16(ES2025)聚焦于迭代器增强、正则表达式改进、模块导入标准化、Promise 工具方法与底层数值类型补齐等方向。
1. Iterator Helpers(迭代器增强)
原生迭代器终于可以像数组一样链式调用了,无需再借助 lodash 或手写工具函数。
function* range(start, end) {
for (let i = start; i < end; i++) yield i;
}
const result = range(1, 10)
.filter(x => x % 2 !== 0)
.map(x => x ** 2)
.take(3)
.toArray();
console.log(result); // [1, 9, 25]
常用方法一览
| 方法 | 说明 |
|---|---|
.map(fn) | 对每个元素执行映射 |
.filter(fn) | 过滤符合条件的元素 |
.take(n) | 取前 n 个元素 |
.drop(n) | 跳过前 n 个元素 |
.flatMap(fn) | 映射后展平一层 |
.reduce(fn, init) | 累计归约 |
.toArray() | 收集为数组 |
.forEach(fn) | 遍历(无返回) |
.some(fn) / .every(fn) | 条件判断 |
.find(fn) | 查找第一个匹配元素 |
链式组合示例
function* fibonacci() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
// 前 20 个斐波那契数中,大于 100 的偶数
const result = fibonacci()
.take(20)
.filter(x => x > 100)
.filter(x => x % 2 === 0)
.toArray();
console.log(result); // [144, 2584]
为什么重要
- 惰性求值:只在真正需要时才计算,适合无限序列
- 链式调用:比
for...of循环更声明式 - 与
Generator配合天然流畅
2. RegExp 相关增强
ES2025 一次性为正则表达式带来了三项改进。
RegExp.escape()
把用户输入安全地转义为正则字面量:
const keyword = 'price: $9.99 (50% off)';
const safe = RegExp.escape(keyword);
const re = new RegExp(safe);
console.log(re.test('price: $9.99 (50% off)')); // true
实际场景
function highlight(text, keyword) {
const re = new RegExp(RegExp.escape(keyword), 'gi');
return text.replace(re, '<mark>$&</mark>');
}
highlight('a+b=c, a+b>d', 'a+b');
// '<mark>a+b</mark>=c, <mark>a+b</mark>>d'
Duplicate named capture groups
以前正则中的命名捕获组不能重名,即使在不同的 | 分支中也不行。现在放开了:
const dateRe = /(?<year>\d{4})-(?<month>\d{2})|(?<month>\d{2})\/(?<year>\d{4})/;
'2025-06'.match(dateRe).groups; // { year: '2025', month: '06' }
'06/2025'.match(dateRe).groups; // { year: '2025', month: '06' }
RegExp Modifiers(内联标志)
在正则表达式局部区域启用/禁用标志:
// 只对 hello 部分忽略大小写
const re = /(?i:hello)\s+world/;
re.test('HELLO world'); // true
re.test('hello WORLD'); // false(world 部分仍区分大小写)
3. Promise.try()
统一封装"可能同步抛错、也可能返回 Promise"的函数,始终返回 Promise:
function getConfig(useCache) {
if (!useCache) throw new Error('缓存不可用');
return fetch('/api/config').then(r => r.json());
}
// 以前:同步抛错不会被 .catch 捕获
// getConfig(false).catch(...) // ❌ 同步异常直接炸了
// 现在:Promise.try 统一包装
Promise.try(() => getConfig(false))
.then(config => console.log(config))
.catch(err => console.error(err.message)); // ✅ '缓存不可用'
对比传统写法
// 旧写法 1:手动包一层
new Promise(resolve => resolve(getConfig(false)));
// 旧写法 2:async 立即执行
(async () => getConfig(false))();
// 新写法:语义最清晰
Promise.try(() => getConfig(false));
4. JSON Modules 与 Import Attributes
JSON Modules
直接以 ES Module 的方式导入 JSON 文件:
import config from './config.json' with { type: 'json' };
console.log(config.version); // '1.0.0'
Import Attributes
通过 with 关键字声明导入资源的类型:
import data from './data.json' with { type: 'json' };
import styles from './theme.css' with { type: 'css' };
动态导入同样支持
const config = await import('./config.json', { with: { type: 'json' } });
价值
- 取代以前的
assert(已废弃),改用with - 让模块加载器可以在加载前知道资源类型
- JSON 导入不再需要
fetch+JSON.parse的样板代码
5. Float16 支持
新增 Float16Array 类型数组、DataView 相关读写方法以及 Math.f16round。
const f16 = new Float16Array([1.5, 2.7, 3.14]);
console.log(f16); // Float16Array [1.5, 2.69921875, 3.140625]
console.log(f16.BYTES_PER_ELEMENT); // 2
// 半精度浮点取整
console.log(Math.f16round(1.337)); // 1.3369140625
// DataView 读写
const buffer = new ArrayBuffer(2);
const view = new DataView(buffer);
view.setFloat16(0, 3.14);
console.log(view.getFloat16(0)); // 3.140625
使用场景
- 机器学习推理(WebGPU / WebNN 常用 FP16)
- 节省内存,适合海量浮点数据传输
- 与 GPU shader 数据格式对齐
6. New Set Methods(Set 集合方法)
注意:TC39 Finished Proposals 将 Set 新方法的 Expected Publication Year 标注为 2025。但由于主流浏览器在 2024 年已广泛实现,部分资料(包括本专栏 ES15 篇)将其归入 ES2024。此处不再重复展示完整示例,详见 ES15(ES2024)第 6 节。
新增的方法包括:
union()/intersection()/difference()/symmetricDifference()isSubsetOf()/isSupersetOf()/isDisjointFrom()
7. Redeclarable global eval vars
修正了一个长期行为不一致问题:通过 eval 引入的全局 var 变量现在可以被重新声明。
eval('var x = 1');
eval('var x = 2'); // 以前在严格模式下可能异常,现在统一允许
这主要是语言一致性修复,日常编码几乎不会直接感知。
总结
| 特性 | 说明 | 重要性 |
|---|---|---|
| Iterator Helpers | 迭代器链式处理 | ⭐⭐⭐⭐⭐ |
RegExp.escape() | 安全转义正则特殊字符 | ⭐⭐⭐⭐ |
| Duplicate named capture groups | 正则分支中允许同名捕获组 | ⭐⭐⭐ |
| RegExp Modifiers | 正则内联标志 | ⭐⭐⭐ |
Promise.try() | 统一同步/异步入口 | ⭐⭐⭐⭐ |
| JSON Modules + Import Attributes | 标准化资源导入 | ⭐⭐⭐⭐ |
| Float16 | 半精度浮点类型 | ⭐⭐⭐ |
| New Set Methods | 原生集合运算(详见 ES15) | ⭐⭐⭐⭐⭐ |
| Redeclarable eval vars | 语言一致性修复 | ⭐⭐ |
ES16 的核心趋势是:让常见的工程模式(迭代器处理、模块导入、正则构建)原生化,减少样板代码和第三方依赖。