Array.find+arrow function - Stack Overflow
我想大声告诉你
我想大声告诉你 2017-06-26 10:54:10
0
2
910

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

我想大声告诉你
我想大声告诉你

reply all(2)
小葫芦
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

仅有的幸福

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template