Several methods that do not change the array itself, add 1 to the experience of operating the array

toReversed

is the copy method version corresponding to the reverse() method. Returns a new array with the elements reversed.

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

toSorted()

Copy method version of the sort() method. Returns a new array with elements in ascending order

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()

A duplicated version of the splice() method. Returns a new array with some elements removed and/or replaced at the given index.

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

The with() method uses square brackets to modify the copy method version of the specified index value. It returns a new array with the value at the specified index replaced by the new value.

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]

Guess you like

Origin blog.csdn.net/qq_42816270/article/details/132656626