跳至主要內容

ES14新增内容

黄曦大约 1 分钟JavaScriptES14ES2023

ES14(ECMAScript 2023)新特性

从数组末尾查找元素

新增两个方法:.findLast().findLastIndex(),它们从数组的最后一个元素开始查找。这些方法可以与现有的 .find().findIndex() 方法进行对比。

const arr = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }];

// find vs findLast
console.log(arr.find(n => n.value % 2 === 1)); // { value: 1 }
console.log(arr.findLast(n => n.value % 2 === 1)); // { value: 3 }

// findIndex vs findLastIndex
console.log(arr.findIndex(n => n.value % 2 === 1)); // 0
console.log(arr.findLastIndex(n => n.value % 2 === 1)); // 2

Hashbang 语法

Hashbang 语法允许在脚本开头添加 #! 符号,用于指定脚本的运行环境。注意,Windows 系统不支持此功能。

#!/usr/bin/env node
console.log("JavaScript");

将 Symbols 作为 WeakMap 的键

WeakMap 现在允许使用 Symbol 作为键,这可以用来创建私有属性。Symbol 是 ECMAScript 中唯一的原始类型,提供唯一值,因此可以用作键来避免直接关联到对象。

const weak = new WeakMap();
const key = Symbol('my ref');
const someObject = { a: 1 };
weak.set(key, someObject);
console.log(weak.get(key));

通过复制改变数组

Array.prototype 上新增了几个方法,这些方法通过返回带有更改的新数组副本而不是更新原始数组来修改数组。

  • .toReversed()
  • .toSorted(compareFn)
  • .toSpliced(start, deleteCount, …items)
  • .with(index, value)
const sequence = [1, 2, 3];
sequence.toReversed(); // [3, 2, 1]
sequence; // [1, 2, 3]

const outOfOrder = [3, 1, 2];
outOfOrder.toSorted(); // [1, 2, 3]
outOfOrder; // [3, 1, 2]

const array = [1, 2, 3, 4];
array.toSpliced(1, 2, 5, 6, 7); // [1, 5, 6, 7, 4]
array; // [1, 2, 3, 4]

const correctionNeeded = [1, 1, 3];
correctionNeeded.with(1, 2); // [1, 2, 3]
correctionNeeded; // [1, 1, 3]