这是我的任务:
为您预先编写了一个以名称和属性(prop)为参数的lookUpProfile函数。
该函数应检查name是否是实际联系人的名字,并且给定属性(prop)是该联系人的属性。
如果两者都为true,则返回该属性的“值”。
如果姓名与任何联系人都不对应,则返回“没有此类联系人”
如果prop不符合与姓名匹配的联系人的任何有效属性,则返回“无此属性”
第3,4段执行得很好,请告诉我为什么第1,2段不起作用。
代码如下:
//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 (name === contacts[i].firstName) {
if (prop === contacts[i][prop]) {
return contacts[i][prop];
} else {
return "No such property";
}
} else {
return "No such contact";
}
}
// Only change code above this line
}
}
// Change these values to test
your function
lookUpProfile("Akira", "likes");
答案 0 :(得分:1)
您的代码中有2个问题:
'likes'
)与值(某个数组)进行比较,该值永远不会为真。x
function lookUpProfile(name, prop) {
for (var i = 0; i < contacts.length; i++) {
if (name === contacts[i].firstName) {
if (contacts[i][prop]) {
return contacts[i][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
}