JavaScript 使用迴圈語句查詢通訊錄(https://www.w3cschool.cn/>程式設計實戰列表個人答案分享 )
題目和要求:
我們有一個聯絡人列表,裡面儲存著不同聯絡人的陣列物件。
函式 lookUpProfile
有兩個預定義引數:firstName
值和prop
屬性 。
該函式應檢查firstName是實際聯絡人的firstName,給定的屬性(prop)是該聯絡人的屬性。
如果它們都存在,函式返回prop
屬性對應的值。
如果firstName
值不存在,返回 "No such contact"
。
如果prop
屬性不存在,返回 "No such property"
。
程式碼:
//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){
for(var i=0; i<contacts.length; i++){
if(contacts[i].firstName==firstName){
var a = 1;
if(contacts[i].hasOwnProperty(prop)){
var b=1;
return contacts[i][prop];
}
}
}
if(a!=1){
return "No such contact";
}
if(b!=1){
return "No such property";
}
}
// Change these values to test your function
lookUpProfile("Sherlock", "likes");