ES2023 新特性

1. findLast()和findLastIndex()

findLast()findLastIndex()方法与find()findIndex()方法相同,只是它们从数组的末尾开始搜索。

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(arr.find(item => item > 5)) // 6
console.log(arr.findLast(item => item > 5)) // 9

console.log(arr.findIndex(item => item > 5)) // 5
console.log(arr.findLastIndex(item => item > 5)) // 8

2. 复制改变数组的方法

Array.prototype上的reverse()、sort()和splice()会改变原数组。于是新提案提出了toReversed()、toSorted()、toSpliced()和with()

2.1 toReversed()

toReversed()方法返回一个新数组,该数组是原数组的反转。

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const reversed = arr.toReversed()

console.log(arr) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(reversed) // [9, 8, 7, 6, 5, 4, 3, 2, 1]

2.2 toSorted()

toSorted()方法返回一个新数组,该数组是原数组的排序。

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const sorted = arr.toSorted((a, b) => b - a)

console.log(arr) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(sorted) // [9, 8, 7, 6, 5, 4, 3, 2, 1]

2.3 toSpliced()

toSpliced()方法返回一个新数组,该数组是原数组的splice()。

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const spliced = arr.toSpliced(2, 3, 10, 11, 12) // 从索引2开始删除3个元素,并插入10, 11, 12

console.log(arr) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(spliced) // [1, 2, 10, 11, 12, 6, 7, 8, 9]

2.4 with()

with()方法修改指定索引值。它会返回一个新数组,其指定索引处的值会被新值替换。原数组不会被修改。

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const withArr = arr.with(2, 11, 12)

console.log(arr) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(withArr) // [1, 2, 11, 12, 4, 5, 6, 7, 8, 9]

3. Symbol作为WeakMap的key

在ES2023中,Symbol可以作为WeakMap的key。

const weak = new WeakMap()

const key = Symbol('ref')
weak.set(key, 'ES2023')

console.log(weak.get(key)) // ES2023

4. Hashbang语法

Hashbang注释是一种特殊的注释语法,其行为与单行注释 // 完全一样,只是它以#!开头,并且只在脚本或模块的最开始处有效。注意#!标志之前不能有任何空白字符。注释由#!之后的所有字符组成直到第一行的末尾;只允许有一条这样的注释。JavaScript 中的 hashbang 注释类似于 Unix 中的 shebang,它提供了一个特定的 JavaScript 解释器的路径,用它来执行这个脚本。

#!/usr/bin/env node

console.log('Hello World')

这样就可以直接运行脚本代码了:

$ node hello.js
Hello World