
ES14 (ES2023)新特性
文章类型:Javascript
发布者:hp
发布时间:2025-03-11
1:数组不可变方法:
toSorted():返回排序后的新数组,不修改原数组
toReversed():返回逆序后的新数组,不修改原数组
toSpliced(start, deleteCount, ...items):返回删除或插入元素后的新数组
const arr = [3, 1, 4];
const sorted = arr.toSorted((a, b) => a - b); // [1, 3, 4]
const reversed = arr.toReversed(); // [4, 1, 3]
console.log(arr); // 原数组不变:[3, 1, 4]
2:findLast 与 findLastIndex:从数组末尾向前搜索元素,返回首个匹配项或其索引
const nums = [2, 4, 6, 8, 5];
const lastEven = nums.findLast(n => n % 2 === 0); // 8
const index = nums.findLastIndex(n => n === 5); // 4
3:Shebang 支持:允许在 JavaScript 文件首行使用 #! 声明解释器
#!/usr/bin/env node
console.log('Hello from CLI!');
4:WeakMap 支持符号键:允许将 Symbol 类型作为 WeakMap 的键
const key = Symbol('metadata');
const weakMap = new WeakMap();
weakMap.set(key, { data: 'secret' });
1:优先采用:数组不可变方法提升代码可预测性,减少副作用 :。
2:性能优化:findLast 替代反向遍历逻辑,简化代码。
3:慎用场景:WeakMap 符号键需确保内存管理可控