【前端ES】ECMAScript 2023 (ES14) 引入了多个新特性,简单介绍几个不为人知但却好用的方法

发布于:2025-02-19 ⋅ 阅读:(22) ⋅ 点赞:(0)
  1. Array.prototype.toSorted()

返回一个新的已排序数组副本,不改变原数组。

let arr = [5, 4, 2, 3, 1];
console.log(arr.toSorted()); // [1, 2, 3, 4, 5]
  1. Array.prototype.with()

允许根据索引修改数组中的单个元素,并返回新数组。

const arr = ["I", "am", "rex"];
const newArr = arr.with(2, "Ape Man");
console.log(newArr); // ["I", "am", "Ape Man"]
  1. Array.prototype.toReversed()

类似于 reverse(),但返回一个新的数组而不是原地操作。

console.log(["1", "2", "3", "4", "5"].toReversed()); // ['5', '4', '3', '2', '1']
  1. Array.prototype.findLast

从数组中获取最后一个匹配元素的实例。

const arr = [24, 34, 55, 75, 10, 77];
console.log(arr.findLast(element => element % 2 === 0)); // 10
  1. Array.prototype.findLastIndex()

与 findLast() 类似,但返回匹配元素的索引。

const arr = [24, 34, 55, 75, 10, 77];
console.log(arr.findLastIndex(element => element % 2 === 0)); // 4
  1. Array.prototype.toSpliced()

类似于数组的 splice 方法,但返回一个新数组。

const arr = [1, 2, 3, 4];
console.log(arr.toSpliced(2, 0, 'a', 'b')); // [1, 2, 'a', 'b', 3, 4]
  1. Hashbang 支持

允许在脚本文件的第一行使用 #! 开头来指定解释器路径。这对于运行时环境(如 Node.js)特别有用。

#!/usr/bin/env node
console.log("This is a script with hashbang support.");
  1. 使用 Symbol 作为 WeakMap 键

扩展了 WeakMap 和 WeakSet 的功能,允许使用 Symbol 作为键。

const weakMap = new WeakMap();
const key = Symbol('key');
const obj = {};
weakMap.set(key, obj);
console.log(weakMap.get(key)); // 输出: {}
  1. Intl.NumberFormat.prototype.formatRangeToParts

提供了一种方法来格式化数字范围,并返回格式化的部分数组。

const numberFormat = new Intl.NumberFormat('en', { style: 'currency', currency: 'USD' });
console.log(numberFormat.formatRangeToParts(5, 10));
  1. Intl.NumberFormat.prototype.formatRangeToParts

提供了一种方法来格式化数字范围,并返回格式化的部分数组。

const numberFormat = new Intl.NumberFormat('en', { style: 'currency', currency: 'USD' });
console.log(numberFormat.formatRangeToParts(5, 10));
  1. Error Cause

在创建错误对象时可以传递一个原因对象,帮助追踪错误来源。

try {
  throw new Error("An error occurred", { cause: "Some additional context" });
} catch (e) {
  console.error(e.message, e.cause); // 输出: An error occurred Some additional context
}
  1. FinalizationRegistry Cleanup Callbacks

提供了一个机制来注册回调函数,当垃圾回收器清除注册表中的条目时调用。

const registry = new FinalizationRegistry((heldValue) => {
  console.log(`Cleaned up ${heldValue}`);
});
let obj = {};
registry.register(obj, "some value");
obj = null; // 假设此时 obj 被垃圾回收
  1. Promise.withResolvers()

返回一个新的 Promise 对象和对应的 resolve/reject 函数。

const { promise, resolve, reject } = Promise.withResolvers();
promise.then(value => console.log(value)); // 当 resolve 被调用时输出值
resolve("resolved value");
  1. Top-Level Await in Modules

允许在模块顶层使用 await,而不仅仅是在异步函数内部。

await someAsyncFunction(); // 直接在模块顶层使用 await
  1. Logical Assignment Operators

引入了逻辑赋值操作符:&&=||=??=,这些操作符结合了逻辑运算与赋值。

let a; a &&= 5; // 等价于 a = a && 5;

  1. Numeric Separators

允许在数字字面量中使用下划线 _ 作为千位分隔符以提高可读性。

const budget = 1_000_000_000_000; // 一千亿
  1. Class Fields and Static Class Features

支持类字段声明和静态类特性,简化类定义。

class MyClass {
  field = "a field";
  static staticField = "a static field";
}