ES6的find函数出现之前,我们是这样写的:
const persons= [{
name: 'Judy', sex: 'Female'
}, {
name: 'Tom', sex: 'Male'
}, {
name: 'Grace', sex: 'Female'
}]
function findPerson(name,sex) {
for(let i = 0; i<persons.length; ++i) {
if(persons[i].name=== name&& persons[i].sex === sex) {
return persons[i];
}
}
};
findPerson('Judy','Female');
有了find之后,我们只需要这样写就行了:
person= persons.find(person => person.name ==='Judy' && person.sex === 'Female');
console.log(person); // {name: "Judy", sex: "Female"}