我们有一个对象数组,里面存储着通讯录。
函数 lookUp 有两个预定义参数:firstName值和prop属性 。
函数将会检查通讯录是否存在一个联系人的firstName属性等于firstName值,还会检查对应联系人是否存在 prop属性。
如果它们都存在,函数返回prop属性对应的值。
如果firstName 值不存在,返回 "No such contact"。
如果prop 属性不存在,返回 "No such property"。
FreeCodeCamp
//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 lookUp(firstName, prop){ //method 1
var result = "No such contact";
for(var i = 0 ; i < contacts.length; i++){
var paraName = contacts[i].firstName;
var hasProp = contacts[i].hasOwnProperty(prop);
if(paraName === firstName ){
if(hasProp){
result = contacts[i][prop];
break;
}else{
result = "No such property";
break;
}
}
}
return result;
}
function lookUp(firstName, prop){ //method 2
var result = "No such contact";
for(var i = 0 ; i < contacts.length; i++){
var paraName = contacts[i].firstName;
var hasProp = contacts[i].hasOwnProperty(prop);
if(paraName === firstName ){
if(hasProp){
return contacts[i][prop];
//return result;
}else{
return "No such property";
}
}
}
return "No such contact";
}
function lookUp(firstName, prop){//method 3
// Only change code below this line
for(var i=0;i<4;i++){
if(contacts[i].firstName==firstName){
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
//lookUp("Sherlock", "likes");
lookUp("Bob", "address");