【JavaSciript 源码:find和findIndex(ES6)的源码函数封装 】(面试高频题)

477 阅读1分钟

1.两个函数特点:

1.find函数主要使用用于查找某个符合判断条件的元素item,并return出去,函数执行完毕不影响原数组,开辟了一个新的空间将元素存储起来,故使用过程中需要定义一个变量去接收。

2.findIndex函数主要是将符合条件的item元素的下标索引值return出去,同样也是不改变原数组,开辟新空间储存这个下标值,调用时需要定义一个变量去接收。

1.find函数源码

Array.prototype.myFind = function(returnItemFunc){
      //此时你要了解到,我们平时在调用find方法时,是以arr.find的方式调用函数,故要知道的是,封装函数内的this其实指向的就是要调用该函数的数组
      for(let i = 0;i<this.length;i++){
        //从这里可以看出,returnItemFunc实际上是一个回调函数。
        //那么回调函数的话,最重要的还是当回调函数返回为true的时候,我们把对应符合条件的元素返回出去,我们上面说到this指向的是调用该函数的数组,namethid[i]指的就是该数组对应i下标的元素。
        //其次,这里面这个回调函数为什么传入两个实参,都知道arr.find(function(item,index){ return .... })
        if(returnItemFunc(this[i],i)){
          return this[i]
        }
      }
    }
    
    var arr = [1,2,3,4]
    var res = arr.myFind(function(item,index){
      return item === 3
    })
    
    console.log(res) // 3
    

2.findIndex函数源码

//findIndex则是返回符合条件为true的元素下标。
    //源码基本一致,只是return的是index下标而已
    Array.prototype.myfindIndex = function(returnItemIndexFunc){
      for(let i = 0;i<this.length;i++){

        if(returnItemIndexFunc(this[i],i)){
          return i
        }
      } 
    }
    var res2 = arr.myfindIndex(function(item,index){
      return item === 1
    })
    console.log(res2) // 0