• JS中findIndex方法的使用场景以及与find的差别


    1. typedArray.find:找到返回被找元素,找不到返回undefined
    2. typedArray.findIndex()是JavaScript中的内置函数,如果值满足函数中给定的条件,则该函数用于返回tyedArray中的索引,否则返回-1
    typedarray.findIndex(callback)

    参数:它采用参数“callback”函数,该函数检查提供的条件满足的typedArray的每个元素。回调函数采用以下指定的三个参数:

    • element:它是元素的值。
    • index:它是元素的索引。
    • array:遍历的是数组。

    返回值:如果元素满足函数提供的条件,则返回数组中的索引;否则,返回-1。

    findIndex 示例:

    1. //示例1
    2. const arr = [1, 2, 3, 4, 5, 3, 3, 2, 4, 5 ]
    3. // 写法1
    4. const index = arr.findIndex(item => {
    5. return item > 2
    6. })
    7. console.log(index) // 2
    8. // 写法2
    9. const index = arr.findIndex(item => item > 2)
    10. console.log(index) // 2
    11. --------------------------------------------------------------------
    12. //示例2
    13. const findArr = [
    14. { name: '张三', no: '15' },
    15. { name: '李四', no: '10' },
    16. { name: '王五', no: '5' }
    17. ]
    18. const fIndex = findArr.findIndex(({ name }) => name === '张三')
    19. console.log(fIndex) // 0
    20. const ffIndex = findArr.findIndex(({ name }) => name === '小付')
    21. console.log(ffIndex);// -1

    find示例:

    1. //示例1
    2. const arr = [
    3. {
    4. name: '张三',
    5. age: 18
    6. },
    7. {
    8. name: '李四',
    9. age: 20
    10. },
    11. {
    12. name: '王五',
    13. age: 22
    14. }
    15. ]
    16. const val = arr.find(item => {
    17. return item.age === 20
    18. })
    19. //换种写法
    20. const val = arr.find(item => item.age === 20)
    21. console.log(val)
    22. // {
    23. name: '李四',
    24. age: 20
    25. }
    26. --------------------------------------------------------------------
    27. //示例2
    28. const findArr = [
    29. { name: '张三', no: '15' },
    30. { name: '李四', no: '10' },
    31. { name: '王五', no: '5' }
    32. ]
    33. const ffind = findArr.find(({ name }) => name === '张三')
    34. console.log(ffind) // { name: '张三', no: '15' }
    35. const fffind = findArr.find(({ name }) => name === '小付')
    36. console.log(fffind);// undefined

    实际应用场景:就比如查找ID改变选中状态等等

    1. <view class="todo-list" :class="{ 'todo--finish': item.checked }"
    2. v-for="(item, index) in listData" :key="index" @click="finish(item.id)">
    1. //点击列表表示已完成
    2. finish (id) {
    3. let index = this.list.findIndex((item) => item.id === id)
    4. this.list[index].checked = !this.list[index].checked
    5. },

     

  • 相关阅读:
    java114-Calendar类方法before
    16.一篇文章学会django模型的使用
    特征融合篇 | YOLOv8 引入中心化特征金字塔 EVC 模块 | 《Centralized Feature Pyramid for Object Detection》
    【Day27】输入输出流一
    Spring集成hazelcast实现分布式缓存
    【QCM2150】WCN3680 WFA 11ac STA 5.2.1/5.2.61测试失败
    spring的循环依赖
    [云原生案例2.2 ] Kubernetes的部署安装 【单master集群架构 ---- (二进制安装部署)】网络插件部分
    数据结构—链表
    JVM和Java体系结构
  • 原文地址:https://blog.csdn.net/ONLYSRY/article/details/128127428