数组新增拷贝、查询方法

数组 sort、reverse、splice 方法都是破坏性操作

会改变原始数组

const arr = [1, 2, 3]

arr.reverse() // [3,2,1]

arr // [3, 2, 1] - 原数组被改变了
1
2
3
4
5

对于使用 react 的 Immutable 数据编程来说是非常不友好的

所以 TC39 组织提供了对应的非破坏性操作

# toSorted、toReversed、toSpliced

toSorted 对应 sorted

toReversed 对应 reverse

toSpliced 对应 splice

以上不改变原始数组外,使用上没差别

const arr = [1, 2, 3]

arr.toSpliced(0, 2, 'x') // ['x', 3]

arr // [1, 2, 3] - 原数组不变
1
2
3
4
5

目前 Chrome 110 开始支持,其他浏览器部分版本也支持

接口详情及各浏览器支持 (opens new window)

# with 方法

这个方法对应数组的索引操作赋值

with 接收两个参数:数组索引及索引位置上的值

const arr = [1, 2, 3]

arr[1] = 10 // arr 数组被改变

arr.with(1, 10) // [1, 10, 3]

arr // [1, 2, 3] arr 未改变
1
2
3
4
5
6
7

# findLast、findLastIndex 查询方法

这两个方法与 find、findIndex 形成了首尾呼应

从数组尾端查询元素及索引

参数是一个处理函数

const arr = [1, 2, 3]

arr.findLast(v => v < 3) // 2

arr.findLastIndex(v => v < 3) // 1
1
2
3
4
5

# 小结

数组 toSorted、toReversed、toSpliced、with 方法直到最近才注意到

with 方法有点惊艳,这样以后操作数组就可以完全通过方法进行了

对于不支持的浏览器进行 polyfill 即可

findLast、findLastIndex 对于性能优化会有帮助

一些场景查询方向不同,性能差距很大

扫一扫,微信中打开

微信二维码