以下是我想要达到的目标:
*该函数应检查firstName是否为实际联系人的firstName,并且给定属性(prop)是该联系人的属性。
如果两者都为真,则返回"值"该财产。
如果firstName与任何联系人不对应,则返回"没有此类联系人"
如果道具不对应任何有效的属性,则返回"没有这样的属性" *
我的代码:
//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(firstName, prop){
// Only change code below this line
for (var i = 0; i<prop.length; i++){
if(contacts.hasOwnProperty(firstName)=== true && contacts.hasOwnProperty(prop)=== true){
return firstName[i].prop;
}
else if(firstName !==firstName[i].prop) {
return "No such contact";
}
else if(prop !== "prop"){
return "No such property";
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
答案 0 :(得分:0)
您可以使用Array.prototype.find
过滤掉firstName
的联系人 - 请参阅下面的演示:
// 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(firstName, prop) {
var found = contacts.find(function(e){
return e.firstName === firstName;
});
if(!found) {
return "No such contact";
} else {
if(prop in found) {
return found[prop];
} else {
return "No such property";
}
}
}
// Change these values to test your function
var result = lookUpProfile("Akira", "likes");
console.log(result);