问题
I'm trying to write a function that will iterate through a variable holding objects. If you pass in a first name that is an object property, you should get true. If not, you should get false. However, no matter what I pass through the function, I always get false. Any help is greatly appreciated.
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function attempt(firstName){
for(var i = 0;i < contacts.length; i++){
if(contacts[i].firstName==firstName){
return true;
} else {
return false;
}
}
}
回答1:
Think through the logic for a moment: What happens on the first loop? What does the function do in response to the if
/else
? Right! It returns true
or false
right away, without looping through the remaining entries at all.
You need to remove the else
entirely and move return false
to outside the loop:
function attempt(firstName) {
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName == firstName) {
return true;
}
}
return false;
}
Side note: Array#some is designed for exactly this use case:
function attempt(firstName) {
return contacts.some(function(entry) {
return entry.firstName == firstName;
});
}
来源:https://stackoverflow.com/questions/41913027/trying-to-use-a-for-loop-with-if-else-statement-in-objects