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
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, returnundefined
.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
When the arrow function has only one parameter, the parentheses can be omitted