• 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. },

     

  • 相关阅读:
    简单分支(下)
    TS 类型体操 之 extends,Equal,Alike 使用场景和实现对比
    基于Linux的驱动开发:内核模块传参、内核到处符号表、字符设备驱动
    (10)在以下横线处写出使用v_stu_m视图查询总学分大于10的学生的查询语句,查询 果如图9.12所示。
    什么是对象的原型?
    windows关闭copilot预览版
    操作系统实训题目
    vue中预览xml并高亮显示
    用DIV+CSS技术设计的网页与实现制作【体育文化】dreamweaver学生网页设计
    第十八章:Swing自述
  • 原文地址:https://blog.csdn.net/ONLYSRY/article/details/128127428