所以我有在 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");`
最佳答案
这就是为什么正确的代码缩进很重要。您的 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");
关于javascript - 为什么 Prop 显示未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003959/