ECMAScript 2023 的几个新特性

146 阅读2分钟

介绍

ECMAScript 2023 的最终版本预计将于今年 6 月底发布。最新举行的一次 TC39 会议基本已经确定 了 ECMAScript 2023 的新功能列表,预计不会再有任何重大的编辑更改。

本文整理了在 2023 年进入 Stage 4 的几个提案。按照 TC39 的运作流程,每个提案都从 Stage 0 开始,进入 Stage 4 则意味 着该提案已被 ECMAScript 编辑签署同意意见,成为了事实上的标准特性。

模块块(Module Blocks)

模块块是一种新的代码结构,允许你创建内联的、封闭的模块。模块块使用新的 module 关键字声明,并可以与 import 和 export 一起使用。

const mathModule = module {
  export const add = (a, b) => a + b;
  export const subtract = (a, b) => a - b;
};

import { add, subtract } from mathModule;

console.log(add(1, 2)); // 输出 3
console.log(subtract(5, 3)); // 输出 2

Array.prototype.groupBy 方法

这个新方法允许你根据元素的某个属性或计算结果将数组分组。它接受一个回调函数,该函数返回用于分组的键。

const people = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 30 },
];

const groupedByAge = people.groupBy(person => person.age);

console.log(groupedByAge);
// 输出:
// {
//   25: [{ name: 'Bob', age: 25 }],
//   30: [
//     { name: 'Alice', age: 30 },
//     { name: 'Charlie', age: 30 },
//   ],
// }

Array find from last

提案ArrayTypedArray 原型上增加了 findLast()findLastIndex() 方法。它们与 find()findIndex() 做同样的事情,但顺序相反。这两个方法都很方便,可跳过创建临时的重复、突变和混乱的索引减法。

const isEven = (number) => number % 2 === 0;
const numbers = [1, 2, 3, 4];

// from first to the last lookup
console.log(numbers.find(isEven));
// 2
console.log(numbers.findIndex(isEven));
// 1

// from last to the first lookup
console.log(numbers.findLast(isEven));
// 4
console.log(numbers.findLastIndex(isEven));
// 3

Symbols as WeakMap keys

在 JavaScript 中,ObjectsSymbols 被保证是唯一并且不能被重新创建的,这使得它们都是 WeakMapkeys 的理想候选者。以前的版本或规范只允许以这种方式使用 Objects ,但新的 Symbols as WeakMap keys 提案则提出将 non-registered Symbols 添加到允许的键列表中。

const weak = new WeakMap();
const key = Symbol("ref");
weak.set(key, "ECMAScript 2023");

console.log(weak.get(key));
// ECMAScript 2023

Change Array by Copy

Array.prototype 上的 reverse()sort() 和 splice() 方法会就地改变数组。Change Array by Copy 提案添加了那些返回新 copy 方法的等价物 —— toReversed()toSorted() 和 toSpliced()。该提案还添加了一个 with() 方法,该方法返回一个新的数组,其中给定索引处的元素被替换为给定值,以避免使用 bracket notation 的就地突变。

const original = [1, 2, 3, 4];
const reversed = original.toReversed();

console.log(original);
// [ 1, 2, 3, 4 ]

console.log(reversed);
// [ 4, 3, 2, 1 ]
const original = [1, 3, 2, 4];
const sorted = original.toSorted();

console.log(original);
// [ 1, 3, 2, 4 ]

console.log(sorted);
// [ 1, 2, 3, 4 ]
const original = [1, 4];
const spliced = original.toSpliced(1, 0, 2, 3);

console.log(original);
// [ 1, 4 ]

console.log(spliced);
// [ 1, 2, 3, 4 ]
const original = [1, 2, 2, 4];
const withThree = original.with(2, 3);

console.log(original);
// [ 1, 2, 2, 4 ]

console.log(withThree);
// [ 1, 2, 3, 4 ]