With this FreeCodeCamp problem I was stuck for ages but managed to get through it when I changed:
if(contacts[i].firstName === name)
to
if(contacts[i].name === firstName)
Not sure why switching name
and firstName
around worked, can someone explain why? update: added entire code for clarity:
//Setup
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 lookUpProfile(name, prop){
// Only change code below this line
for (var i =0; i <contacts.length; i++) {
if(contacts[i].firstName === name) {
if(contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else
return "No such property";
}
}
return "No such contact"
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
I was thinking that. So this was the code that made me pass.
function lookUpProfile(name, prop){
// Only change code below this line
for (var i =0; i <contacts.length; i++) {
if(contacts[i].firstName === name) {
if(contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else
return "No such property";
}
}
return "No such contact"
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
There are two issues with using the following if
statement:
if(contacts[i].name === firstName)
The first issue is that you are trying to use firstName
as a variable . There is no variable in your code called firstName
and so you'll get an error when you try to use it as one. Instead, firstName
is a property of an object in your array (not to be confused with a standalone variable). This means you can only access firstName
with reference to an object in your array.
The second issue with the above code is contacts[i].name
. In this part of your code contacts[i]
is referring to the i th
object in your code. You are then trying to access the name
property of this given object. However, none of your objects have a name
property - they have a firstName
property, but don't have a name
property. So, when you try and access a property/key that isn't in your object, you'll get undefined
back.
The valid code to use is:
if(contacts[i].firstName === name)
as firstName
is a property of your object (which you are accessing with reference to your object - contacts[i]
) and name
is a variable (an argument of the function) which can be used without any problems.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.