因此,我有此代码在Freecodecamp上运行。无法理解为什么未定义其显示道具。
prop在调用时实际上是从函数中获取值。与prop不同的是,名称不是未定义的名称。
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
switch(name) {
case "Akira":
case "Harry":
case "Sherlock":
case "Kristian":
for ( var j=0; j<contacts.length;j++) {
if(contacts[j].firstName == name) {
return contacts[j][prop];
} else {
console.log("No such contact");
}
}break;
}
}
if (!contacts.hasOwnProperty(prop)) {
console.log("No such property");
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Kristian", "lastName");`
答案 0 :(得分:1)
这就是为什么正确的代码缩进很重要的原因。您的if语句不在函数内,因此prop
在您要使用的范围内不存在。将if语句移至函数lookUpProfile
中,它将不会被定义。
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
if (!contacts.hasOwnProperty(prop)) {
console.log("No such property");
// Only change code above this line
}
switch(name) {
case "Akira":
case "Harry":
case "Sherlock":
case "Kristian":
for (var j = 0; j < contacts.length; j++) {
if(contacts[j].firstName === name) {
return contacts[j][prop];
} else {
console.log("No such contact");
}
} break;
}
}
// Change these values to test your function
lookUpProfile("Kristian", "lastName");