yliu

时来天地皆同力,运去英雄不自由

[javaScript]ES2023 引入非破坏性方法


对于 Array 的一些操作,例如 reverse、sort 等都会改变原数组,ES2023 对以下这些方法进行了拓展,提供了相同功能但是返回新副本的方法。

  • toReversed
  • toSorted
  • toSpliced
  • with

下面进行一个详细的介绍。

toReversed

  • reverse:反转数组元素,但是会改变数组本身
  • toReversed:跟 reverse 功能相同,但是返回新副本不会改变数组本身

示例 1.js

// reverse
const a = [1, 2, 3];
const b = a.reverse();

console.log(a); // [3, 2, 1]
console.log(b); // [3, 2, 1]

// toReversed 👍
const c = [1, 2, 3];
const d = c.toReversed();

console.log(c); // [1, 2, 3]
console.log(d); // [3, 2, 1]

toSorted

  • sort:对数组进行排序,但是会改变数组本身
  • toSorted:跟 sort 方法一样,但是返回新副本

示例 2.js

// sort
const a = [3, 1, 2];
const b = a.sort();

console.log(a); // [1, 2, 3]
console.log(b); // [1, 2, 3]

// toSorted 👍
const c = [3, 1, 2];
const d = c.toSorted();

console.log(c); // [3, 1, 2]
console.log(d); // [1, 2, 3]

toSpliced

  • splice:非常万能的方法可以对数组进行删除、替换数元素以及添加新元素
  • toSpliced:跟 splice 一样,但是操作不会对原数组进行改变

不过,由于 splice 和 toSpliced 的返回值存在以下差异,因此处理它们时似乎需要小心。

  • splice 的返回值被删除值的数组
  • toSpliced 的返回值返回从数组中删除元素的副本

示例 3.js

// splice
const a = [1, 2, 3, 4];
const b = a.splice(1,2);

console.log(a); // [1,4]
console.log(b); // [2,3] 返回值是删除的值排列的值

// toSpliced 👍
const c = [1, 2, 3, 4];
const d = c.toSpliced(1,2);

console.log(c); // [1,2,3,4]
console.log(d); // [1,4] 返回从数组中删除元素的副本

with

在第一个参数中指定数组的索引号,并将该元素替换为第二个参数的值。

JS 已经有一个单独的 with 语句,但它已被弃用,所以它很混乱,因为它与这次添加的数组操作的 with 方法重叠。

示例 4.js

// with 👍
const c = [1, 2, 3, 4];
const d = c.with(1,'👍');

console.log(c); // [1, 2, 3, 4]
console.log(d); // [1, '👍', 3, 4]

最后

这些方法的出现,使得你不需要每次都浅复制,代码看起来很清爽。