ECMAScript 2023(ES14)

2025-02-20 20:00
2025-02-23 12:40
315

核心特性

1. 数组的非破坏性方法

  • toSorted():排序并返回新数组。
javascript
      const arr = [3, 1, 4];
const sorted = arr.toSorted(); // [1, 3, 4],原数组不变

    
  • toReversed():反转数组并返回新数组。
javascript
      const arr = [3, 1, 4];
const reversed = arr.toReversed(); // [4, 1, 3]

    
  • with(index, value):替换指定索引的值并返回新数组。
javascript
      const arr = [3, 1, 4];
const newArr = arr.with(1, 5); // [3, 5, 4]

    
  • findLast()findLastIndex():从数组末尾查找元素或索引。
javascript
      const arr = [3, 1, 4];
const lastEven = [1, 2, 3, 4].findLast(n => n % 2 === 0); // 4

    

2. Shebang 语法支持

允许在脚本首行使用 #! 指定解释器,提升 Node.js 脚本的可执行性

javascript
      #!/usr/bin/env node
console.log("Hello from ES14!");

    

3. Symbol 作为 WeakMap 键

支持将 Symbol 用作 WeakMap 的键,增强数据结构的灵活性

javascript
      const sym = Symbol("key");
const wm = new WeakMap();
wm.set(sym, "value");
console.log(wm.get(sym)); // 'value'

    

4. Intl.ListFormat

国际化列表格式化(如 "A, B, and C")。

javascript
      const list = ["苹果", "香蕉", "橘子"];
const formatter = new Intl.ListFormat("zh", { style: "long", type: "conjunction" });
console.log(formatter.format(list)); // "苹果、香蕉和橘子"

    

总结

ECMAScript 2023(ES14)通过数组非破坏性方法(如 toSorted()、with())提升不可变数据操作,支持 findLast 逆向查找及 Shebang 语法,允许 Symbol 作为 WeakMap 键,优化脚本执行与数据结构灵活性,适用于函数式编程与工程化场景。

评论区
评论区寄了

文章目录

核心特性
1. 数组的非破坏性方法
2. Shebang 语法支持
3. Symbol 作为 WeakMap 键
4. Intl.ListFormat
总结