I have an issue with one line of code which doesn't seem to be doing as expected:
if (name === contacts[i].firstName && contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
It should check if name matches the firstName of the object and if the object has a property of prop - returning the property if both are true. However, this bit of code seems to be skipped over when running test as each result gives me the answer of "No such contact".
// Setup
const 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 lookUpProfile(name, prop) {
// Only change code below this line
for (let i = 0; i < contacts.length ; i++){
if (name === contacts[i].firstName && contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}else if (name !== contacts[i]["firstName"]){
return "No such contact"
}else if (prop !== contacts[i]["prop"])
return "No such property";
}
// Only change code above this line
}
lookUpProfile("Akira", "likes");
There is a solution below which uses a nested IF statement but I want to know why my initial way of trying to solve it doesn't work.
function lookUpProfile(name, prop) {
for (let 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";
}
The problem in full can be accessed here: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup
Aucun commentaire:
Enregistrer un commentaire