I have an array of contacts like this:
var contacts = [{
"firstName": "Akira",
"likes": "beer",
}, // other contacts
and a function for lookups using if/else
that is called like:
lookUpProfile("Akira", "likes");
If function finds both parameter with name "Akira"
and a property "likes"
, it will return "beer"
. If it can't find such name it should return "no such name"
, and if it can't find parameter "likes" it will return "no such property"
.
I would be glad to see your suggestion on how to better write it , but fixing my code would be superb too. ( it returns "undefined"
instead of "no such contact"
)
function lookUpProfile(firstName, prop) {
for (var i = 0; i < contacts.length; i++) {
var name = contacts[i].firstName;
var propz = contacts[i].hasOwnProperty(prop);
if (name == firstName && propz) {
return contacts[i][prop];
} else if (propz !== prop && firstName == name) {
return "no such property";
} else if (firstName !== name && propz == prop) {
return "no such contact";
}
}
}
lookUpProfile("Akira", "lastName");
Thanks!
Aucun commentaire:
Enregistrer un commentaire