函數(shù) lookUp 有兩個(gè)預(yù)定義參數(shù):firstName值和prop屬性 所计。
函數(shù)將會(huì)檢查通訊錄是否存在一個(gè)聯(lián)系人的firstName屬性等于firstName值兔港,還會(huì)檢查對應(yīng)聯(lián)系人是否存在 prop屬性销睁。
如果它們都存在粒梦,函數(shù)返回prop屬性對應(yīng)的值土童。
如果firstName 值不存在唯袄,返回 "No such contact"弯屈。
如果prop 屬性不存在,返回 "No such property"恋拷。
"Kristian", "lastName" 應(yīng)該返回 "Vos"
"Sherlock", "likes" 應(yīng)該返回 ["Intriguing Cases", "Violin"]
"Harry","likes" 應(yīng)該返回一個(gè)數(shù)組
"Bob", "number" 應(yīng)該返回 "No such contact"
"Akira", "address" 應(yīng)該返回 "No such property"
//錯(cuò)誤解法
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
if(contacts.hasOwnProperty(firstName)){
if(contacts.hasOwnProperty(prop)){
return contacts.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");```
```
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){
// Only change code below this line
for(var i=0;i<contacts.length;i++){
if(contacts[i].firstName == firstName){
if(contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}
return "No such property";
}
}
return "No such contact"; //位置是關(guān)鍵资厉!
// Only change code above this line
}
// Change these values to test your function
lookUp("Akira", "likes");```