ES14 的新特性

128 阅读3分钟

1. 由后往前查找数组的方法:findLast() 和 findLastIndex()

findLast()findLastIndex() 这两者是在 ES2023 新加入的数组操作方法,这两者有相近的方法,分别是 find()findIndex

我们可以从字面上理解, find()findIndex 会是从数组开头开始找寻符合条件的元素,而 findLast()findLastIndex() 这两个新的数组方法是从数组的尾部开始查找元素:

  • 如果找到了符合条件的元素, findLast() 方法会返回该元素的值; 如果没有找到符合条件的元素, findLast() 方法会返回 undefined
  • findLastIndex() 它会返回从尾部查找中符合条件的第一个元素的索引; 如果没有找到符合条件的元素, findLastIndex() 方法会返回 -1。
const arr = [6, 16, 25, 20, 17, 13, 33, 10];

// 从 index 0 开始寻找值大于 20 的项目,找到后就停止寻找,并返回值
const result1 = arr.find((x) => x > 20);
console.log(result1); // 25

const result2 = arr.findIndex((x) => x > 20);
console.log(result2); // 2

// 从数组最后开始寻找值大于 20 的项目,找到后就停止寻找,并返回值
const result3 = arr.findLast((x) => x > 20);
console.log(result3); // 33

const result4 = arr.findLastIndex((x) => x > 20);
console.log(result4); // 6

2. 新增 4 个不改动到原数组的操作方法

ES2023 引入了四种新的数组操作方法,这些方法不会修改原始数组,而是会返回一个原始数组的拷贝。这四种方法是:

  • toReversed():将数组中的元素反转(相对应会改变量组的方法: reverse()
const numbers = [1, 2, 3, 4, 5];

// 反转数组
const reversedNumbers = numbers.toReversed();
console.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]
  • toSorted(fn):将数组中的元素排序(相对应会改变量组的方法: sort()
const numbers = [1, 2, 3, 4, 5];

// 将数组排序
const sortedNumbers = numbers.toSorted();
console.log(sortedNumbers); // Output: [1, 2, 3, 4, 5]
  • toSpliced(start, deleteCount, ...items):从数组中指定位置开始删除指定数量的元素,并可选择在删除后新增新元素(相对应会改变量组的方法: splice()
const numbers = [1, 2, 3, 4, 5];

// 删除从数组中索引 2 开始两个元素 - 2 和 3,并在删除后新增 10 和 20
const splicedNumbers = numbers.toSpliced(1, 2, 10, 20);
console.log(splicedNumbers); // Output:  [1, 10, 20, 4, 5]
  • with(index, value):将数组索引处的值,替换为新值
const fruits = ["Apple", "Orange", "Lemon", "Mango", "Cherry"];

// 将 fruits 数组索引 2 的值 "Lemon" 替换为 10
const newFruits = fruits.with(2, "Watermelon");
console.log(newFruits);
// Output: ['Apple', 'Orange', 'Watermelon', 'Mango', 'Cherry']

这些新方法提供了更简洁、更具表达力的方式来操作数组。它们可以帮助我们避免对原始数组进行不必要的修改,从而提高代码的可读性和可维护性。

3. Hashbang 语法(Hashbang Grammar)

Hashbang 注释是一种特殊的注释语法,它会以 #! 开头,后面仅跟着解释器 (interpreter) 的路径,并且只会在脚本或是模块的最开始有效。以下方代码为例,这段代码是告诉系统,用 Node.js 来执行文件:

#!/usr/bin/env node

console.log("Hello world");

4. WeakMap 新增支持 Symbol 作为键名 (key)

WeakMap 是一种与 Map 相似的数据结构,用于储存键值对(key-value pair)。两者的主要差别在于:

  • Map 的键名可以是任何数据类型
  • ES2023 之前,WeakMap 的键名则必须是对象; 而在 ES2023 提出了一项新的提案,允许 WeakMap 使用 Symbol 作为键名