探索JS数组新方法: Array.with()、Array.toSorted()、Array.toReversed() 和 Array.toSpliced()

1,053 阅读2分钟

在Javascript中数组作为引用类型,如果我们想在不修改原始数组的情况下执行splicesort,reverse等方法,那么我们必须首先创建原始数组的副本, 这样我们就不会修改原始数组。

以前的处理方式:

const arr = ["Radha","Krishna"];  
  
// 改变数组元素  
const newArr = [...arr];  
newArr[1] = "Virndavan";  
  
// sort  
const sorted = [...arr].sort(); // 需要额外的操作, [...arr]  
  
// reverse  
const reversed = [...arr].reverse); // 需要额外的操作, [...arr]  
  
// splice  
const filtered = [...arr].splice(0,1); // 需要额外的操作, [...arr]

最近JS新引入了4 个新的 Array 方法,Array.with()、Array.toSorted(),Array.toReversed() 和 Array.toSpliced(),它们可以省去复制原数组的步骤。

Array.with(index, value)

返回一个全新的数组,其中 index 索引处的元素被替换为 value

with() 通过返回一个指定索引处的值被新值替换的新数组,来改变数组中指定索引处的值。原数组不会被修改。这使得你可以以链式调用数组方法的方式来对数组进行操作。

with() 方法永远不会产生稀疏数组。如果原数组是稀疏的,新数组对应的空白索引位置会替换为 undefined

示例:

//改变数组元素
const arr = [1, 2, 3, 4, 5];
console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
//在稀疏数组上使用
const arr = [1, , 3, 4, , 6];
console.log(arr.with(0, 2)); // [2, undefined, 3, 4, undefined, 6]

Array.toSorted()

toSorted()  方法是 sort()方法的复制方法版本。它返回一个新数组,其元素按升序排列。

// 不传入函数
toSorted()

// 传入箭头函数
toSorted((a, b) => { /* … */ })

// 传入比较函数
toSorted(compareFn)

// 內联比较函数
toSorted(function compareFn(a, b) { /* … */ })

Array.toReversed()

toReversed()  方法是 reverse()方法对应的复制版本。它返回一个元素顺序相反的新数组。

const items = [1, 2, 3];
console.log(items); // [1, 2, 3]

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

Array.toSpliced()

toSpliced()  方法是 splice()方法的复制版本。它返回一个新数组,并在给定的索引处删除和/或替换了一些元素。

语法:

toSpliced(start)
toSpliced(start, deleteCount)
toSpliced(start, deleteCount, item1)
toSpliced(start, deleteCount, item1, item2, itemN)

示例:

const months = ["Jan", "Mar", "Apr", "May"];

// 在索引 1 处添加一个元素
const months2 = months.toSpliced(1, 0, "Feb");
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]

// 从第 2 个索引开始删除两个元素
const months3 = months2.toSpliced(2, 2);
console.log(months3); // ["Jan", "Feb", "May"]

// 在索引 1 处用两个新元素替换一个元素
const months4 = months3.toSpliced(1, 1, "Feb", "Mar");
console.log(months4); // ["Jan", "Feb", "Mar", "May"]

// 原数组不会被修改
console.log(months); // ["Jan", "Mar", "Apr", "May"]

结语

由于这些方法是新的,它们支持大多数浏览器,但目前 Firefox 不支持它们,但后续将在所有浏览器中得到支持。

可以点击这里查看支持情况。