Skip to content

ECMAScript 2023 (14)

在 Array.prototype 和 TypedArray.prototype 上引入了 toSortedtoReversedwithfindLastfindLastIndex
在 Array.prototype 上引入了 toSpliced
添加文件开头#!(Hashbang/Shebang 语法)的支持
允许使用 Symbol 的值作为弱集合中的键

特性一览

Array toSpliced 方法

在数组中给定的索引开始移除指定数量的元素,然后在相同的索引处插入给定的元素,返回新数组,不修改原数组。

添加一个元素

js
let wife = ["刻晴", "凌华", "纳西妲", "妮露", "宵宫"];
let wife2 = wife.toSpliced(0, 0, "希儿");
// ['希儿', '刻晴', '凌华', '纳西妲', '妮露', '宵宫']

删除两个元素

js
let wife = ["刻晴", "凌华", "纳西妲", "妮露", "宵宫"];
wife.toSpliced(0, 2);
// ["凌华", "纳西妲", "妮露", "宵宫"]

替换前 3 个元素

js
let wife = ["刻晴", "凌华", "纳西妲", "妮露", "宵宫"];
wife.toSpliced(0, 3, "希儿", "爱莉希雅", "琪亚娜", "荧", "三月七");
// ['希儿', '爱莉希雅', '琪亚娜', '荧', '三月七', '妮露', '宵宫']

toSpliced 总是生成密集数组

稀疏数组会被undefined填充

js
let wife = ["刻晴", , , "妮露", "宵宫"];
wife.toSplice();
// ['刻晴', undefined, undefined, '妮露', '宵宫']

用数组原型 toSpliced 指向非数组对象

会读取 this.length 并将对象对应键的值写入新数组

js
wifeObj = {
  length: 3,
  name: "刻晴",
  gender: "女",
  age: "18",
  0: "名字",
  1: "性别",
  2: "年龄",
};
Array.prototype.toSpliced.call(wifeObj, 0, 0);
// ['名字', '性别', '年龄']

Array/TypedArray toSorted 方法

返回一个新数组,其元素按升序排列(首字母),不修改原数组。

js
const words = ["C", "H", "A", "V"];
const sortedWords = words.toSorted();
// ['A', 'C', 'H', 'V']

const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b));
// [1, 2, 10, 21]

稀疏数组会定义 undefined 排到最后

Array/TypedArray toReversed 方法

返回一个相反顺序排列元素的新数组,不修改原数组。

js
const items = [1, 2, 3];

const reversedItems = items.toReversed();
// [3, 2, 1]

Array/TypedArray with 方法

创建一个新的数组,改变其中一个元素,不修改原数组。

js
const arr = [1, 2, 3, 4, 5];
const newArr = arr.with(2, 6);
// [1, 2, 6, 4, 5]

with类似数组方括号,但不会对原数组进行修改

这是数组方括号方法:

js
const arr = [1, 2, 3, 4, 5];
arr[2] = 6;

Array/TypedArray findLast 方法

反向迭代数组,并返回满足测试函数的第一个元素的值。

js
const wife = [
  { name: "刻晴", age: 18 },
  { name: "凌华", age: 18 },
  { name: "纳西妲", age: 16 },
  { name: "妮露", age: 16 },
  { name: "宵宫", age: 16 },
];
wife.findLast((el) => el.age > 15);
// {name: '宵宫', age: 16}

Array/TypedArray findLastIndex 方法

反向迭代数组,并返回满足测试函数的第一个元素的索引。

js
const wife = [
  { name: "刻晴", age: 18 },
  { name: "凌华", age: 18 },
  { name: "纳西妲", age: 16 },
  { name: "妮露", age: 16 },
  { name: "宵宫", age: 16 },
];
wife.findLastIndex((el) => el.age > 15);
// 4

Hashbang/Shebang 语法

用来指定 JavaScript 解释器的路径,JavaScript 中的 Hashbang 注释类似于 Unix 中的 Shebang。在ES2023标准化之前,NodeJS 已经进行了实现,在传递到 V8 引擎之前会被删除。

!#开头,作用跟//注释完全相同,仅在脚本或模块的文件开头时有效。

js
#!/usr/bin/env node

console.log("Hello world");

当脚本直接在 shell 中运行时 Hashbang 语法才有意义,JavaScript 解释器只会把它当作一个普通的注释

Symbol 值可用作弱集合的键