• js中findIndex()、find()、indexOf()、includes()方法


    1、findIndex( ) 方法

    findIndex方法常用来查找满足条件的第一项索引,找到了就返回该索引,找不到返回-1。

    let arr = [1, 2, 3, 4, 5, 4, 3, 2, 5, 4 ]
     
    let index = arr.findIndex(item => {
        return item > 5
    })
    console.log(index) // 4
     
    // 也可以这么写
    let index = arr.findIndex(item => item > 5)
     
    console.log(index) // 4
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    注意:findIndex会对数组中的每一项执行一个函数来判断是否满足表达式,如果满足条件后,剩下的元素则不再执行。

    2、find( )方法

    find方法用来查找满足条件的第一项,找到了就返回那一项对应的值,找不到返回undefined。

        let arr = [
          {
            name: '测试1',
            id: 1
          },
          {
            name: '测试2',
            id: 2
          },
          {
            name: '测试3',
            id: 3
          }
        ]
     
        let value = arr.find(item => {
          return item.id === 20
        })
        
        // 还可以这么写
        let value = arr.find(item => item.id === 2)
        console.log(val)  
        // {
               name: '测试2',
               id: 2
           }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    和findIndex一样,返回满足条件的值,并且不检测剩余值,只不过findIndex返回的是下标,find方法是返回满足条件的那一个元素,具体怎么使用看场景需要

    注:两个方法都不会改变原数组

    3、indexOf( )方法

    indexOf方法可用来查找满足条件的第一项索引,找到了就返回该索引,找不到返回-1。
    注:startIndex搜索的起始位置默认为0,可选

    let arr = [1, 2, 3, 4];
    console.log(arr.indexOf(2))   //1
    console.log(arr.indexOf(2,2)) //-1
    console.log(arr.indexOf(5))   //-1
    
    • 1
    • 2
    • 3
    • 4

    4、includes( )方法

    includes方法可用来判断一个数组是否包含一个指定的值,有则返回 true,没有则返回false。
    也可以查找字符串中是否包含指定的子字符串。

        let arr = [1, 2, 3, 4];   //数组
        //或
        let arr = '1234';        //字符串
        console.log(arr.includes(2))   //true
    	console.log(arr.includes(5))   //false
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 相关阅读:
    记一次MySQL崩溃修复案例,再也不用删库跑路了
    图解系统:
    计算机网络面试题
    浅识vue的虚拟DOM和渲染器
    Linux防火墙之iptables(上)
    【附源码】计算机毕业设计JAVA学生信息管理系统2021
    每日三题 11.10
    31年前的Beyond演唱会,是如何超清修复的?
    React使用Echarts/Ant-design-charts
    解决Invalid bound statement (not found)错误~
  • 原文地址:https://blog.csdn.net/pipizhou16/article/details/126505252