search

Home  >  Q&A  >  body text

Array.find+arrow function - Stack Overflow

I saw a piece of code yesterday, which is like this:

const pets = [
  { type: 'Dog', name: 'Max'},
  { type: 'Cat', name: 'Karl'},
  { type: 'Dog', name: 'Tommy'},
]

function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === 'Dog' && pets[i].name === name) {
      return pets[i];
    }
  }
}

After using the short method:

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

I checked the arr.find method, the definition is array.find(function(currentValue, index, arr),thisValue)

The above code is passed into pet within pet=pets.find() without parameters. I want to know how this code is implemented? Please help me solve my doubts

我想大声告诉你我想大声告诉你2698 days ago913

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-06-26 10:56:10

    pet = pets.find(function(pet) {
          return pet.type === 'Dog' && pet.name === 'Tommy';
    });

    Convert arrow functions to ES5 and that’s it.

    find is used to find the first array member that meets the conditions. Its parameter is a callback function, and all array members execute the callback function in sequence until the first member whose return value is true is found, and then returns that member. If there are no matching members, return undefined.

    These APIs still require more documentation, as they are all basic knowledge without having to turn around.

    MDN Documentation

    es6 manual

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-26 10:56:10

    pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
    is equivalent to

    pets.find((pet) => {
          return pet.type ==='Dog' && pet.name === 'Tommy';
    });

    When the arrow function has only one parameter, the parentheses can be omitted

    reply
    0
  • Cancelreply