I've been trying to solve this https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup/ with the following code:
function lookUpProfile(name, prop){
for (let a = 0; a < contacts.length; a++) {
if (contacts[a].firstName == name && contacts[a].hasOwnProperty(prop)) {
console.log(contacts[a][prop]);
}
else if (name != contacts[a].firstName) {
return "No such contact";
}
else {
return "No such property";
}
}
However this page https://guide.freecodecamp.org/certifications/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup proposes the following, and it works:
for (var x = 0; x < contacts.length; x++){
if (contacts[x].firstName === name) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
I also tried modifying the above to this:
for (var x = 0; x < contacts.length; x++) {
if (contacts[x].firstName === name && contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
To no avail, though. So my question is, why doesn't my code work? And why is there the need to use nested if statements instead of && operator?
Thank you for your attention.
Aucun commentaire:
Enregistrer un commentaire