關於檢查物件陣列的值與屬性判斷
阿新 • • 發佈:2019-01-26
今天這題相對來說比較難,通過搜尋才明白如何通關。記錄,防止自己忘記。
執行的程式碼如下:
//初始化變數
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"]
},
{
"firstName": "",
"lastName": "Vos",
"number": "unknown",
"likes": ["JQuery", "Game", "Fier"]
}
];
function lookUp(firstName, prop){
// 請把你的程式碼寫在這條註釋以下
for(var i = 0;i<contacts.length;i++){
if(contacts[i].firstName == firstName){
if(contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}
else{
return "No such property";
}
}
}
return "No such contact"; //contacts[i].firstName == firstName不成立時執行,也就包含了
firstName
值不存在的情況// 請把你的程式碼寫在這條註釋以上
}
// 你可以修改這一行來測試你的程式碼
lookUp("Sherlock", "dskhak")
//alert(lookUp("Kristian", "lastName"));
//alert(lookUp("Bob", "number"));
//alert(lookUp("Akira", "address"));