js中find()和findIndex()的区别

243 阅读1分钟

find()和findIndex()方法和filter()类似,表现在他们都是遍历数组,寻找断言函数返回真值的元素 但与filtwer()不同的是,这两个方法会在断言函数找到第一个元素时停止迭代 find()返回匹配的元素,findIndex()返回匹配元素的索引,find()如果没有匹配到元素则返回undefined, 而findIndex()返回-1

  let b=[4,3,2,1,10]

   const a = b.find((x)=>{
       x%5 ==0  
   })
   console.log('a',a)  // undefined,数组中没有7的倍数

   const c =b.find((X)=>{
       X%7 ==0  
   })
   console.log('c ',c) // undefined,数组中没有7的倍数

   const e = b.findIndex((x)=>{
      return x<0  
   })
  console.log('e',e)  // -1  数组中没有负数

   const h =b.findIndex((x)=>{
       return x===3  
   })
   console.log('h',h) // 1  3的值索引为1