2025年6月,ECMAScript 2025正式发布,带来了多项实用新特性:
1. JSON模块导入
现在可以直接导入JSON文件了:
// 静态导入
import config from './config.json' with { type: 'json' };
// 动态导入
const data = await import('./data.json', {
with: { type: 'json' }
});
2. 迭代器辅助方法
更优雅的迭代器处理方式:
const result = ['a', '', 'b', 'c']
.values()
.filter(x => x)
.map(x => x.toUpperCase())
.toArray(); // ['A', 'B', 'C']
3. Set集合运算
新增集合操作方法:
const a = new Set([1, 2]);
const b = new Set([2, 3]);
a.union(b); // Set {1, 2, 3}
a.intersection(b); // Set {2}
4. 正则表达式增强
RegExp.escape('.*?'); // '\\.\\*\\?'
// 内联修饰符
/^x(?i:hello)x$/.test('xHELLOx'); // true
5. Promise.try()
统一同步/异步错误处理:
Promise.try(() => {
const val = syncMayThrow();
return asyncOp(val);
}).catch(handleError);
6. 16位浮点数支持
const f16 = new Float16Array([1.0, 0.5]);
Math.f16round(3.1415); // 近似值
这些新特性让JavaScript更强大、更易用!
背起来,用起来,嗨起来。