不改变数组本身的几个方法,操作数组体验加1

toReversed

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

const arr1 = [1, 2, 3];
const reverseArr = arr1.toReversed()
console.log('reverseArr', reverseArr)
// [ 3, 2, 1 ]
console.log('arr1', arr1)
// [1, 2, 3]

toSorted()

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

const arr2 = [3, 2, 1]
const sortedArr = arr2.toSorted((a, b) => a - b)
console.log('sortedArr', sortedArr)
// [1, 2, 3]
console.log('arr2', arr2)
// [3, 2, 1]

toSpliced()

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

const arr3 = [1, 2, 3]
const spliceArr = arr3.toSpliced(0, 1, 4)
console.log('spliceArr', spliceArr)
// [4, 2, 3]
console.log('arr3', arr3)
// [1, 2, 3]

with

with() 方法是使用方括号便是法修改指定索引值的复制方法版本。它会返回一个新数组,其指定索引处的值会被新值替换。

const arr4 = [1, 2, 3]
const arrWith = arr4.with(0, 4)
console.log('arrWith', arrWith)
// [4, 2, 3]
console.log('arr4', arr4)
// [1, 2, 3]

猜你喜欢

转载自blog.csdn.net/qq_42816270/article/details/132656626