• Find and findIndex are two of ES6’s Array.prototype query methods.

  • They are methods of traversal type in an array that can find qualifying elements or subscripts of qualifying elements in the array.

  • // Declare an array of objects for use in the following example
    var objArr = [
        {
            id: 1.name: 'HELLO'.gender: 0.age: 19
        }, 
        {
            id: 2.name: 'Bye'.gender: 1.age: 20
        },
        {
            id: 3.name: 'IOLIU'.gender: 0.age: 21}]Copy the code
  • find

    • Iterate through the array to find the elements that match the criteria

    • Pass a function as an argument to the find method

    • Array.find(function (item) {retrun condition})eg: objArr.find(function (item) {
          return item.id === 2
      })
      Copy the code
    • The item argument in the passed function represents traversal items, each traversal item retrieved from within find

    • This return passes a conditional statement to find

    • It can be seen that the purpose of functions as parameters in a method is to allow programmers to write the content of a function in the method, and then realize the function of the method

    • ConditionFunc (conditionFunc) conditionFunc (conditionFunc) conditionFunc (conditionFunc) conditionFunc (conditionFunc) conditionFunc (conditionFunc) conditionFunc (conditionFunc) conditionFunc

    • Try encapsulating the find implementation yourself:

    • // Because find is the Array prototype chain method in ES6, therefore:
      Array.prototype.myFind = function (conditionFunc) {
          /* We pass the find function as an argument when we call the find method. ConditionFunc = function (item) {return item. XXX === XXX} */
          // Loop over all the elements in the array
          for (let i = 0; i < this.length; i++) {
              if (conditionFunc(this[i])) {
                  return this[i]
              }
          }
      }
      Copy the code
  • findIndex

    • findIndexThe principle andfindIt’s exactly the same, except infindInside the method, the return that meets the criteria isi, will not be repeated here.