<span style="font-family: 'Microsoft YaHei'; line-height: 18.1818px; white-space: pre-line; background-color: rgb(255, 255, 255);">有一个对象数组,里面存储着通讯录。</span>
函数 lookUp
有两个参数: firstName
和prop
。
函数将会检查通讯录是否存在 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 lookUp(firstName, prop){
for (var i in contacts)
{if (contacts[i].firstName === firstName && prop in contacts[i])
return contacts[i][prop];}
for ( i in contacts)
{ if (prop in contacts[i] ===false)
return "No such property";
}
for ( i in contacts)
{ if (contacts[i].firstName !== firstName)
return "No such contact";}
}
// Change these values to test your function
lookUp("Akira", "address");
关于属性名和属性值:
以下方法转自某网友的代码,使用hasOwnProperty:是用来判断一个对象是否有你给出名称的属性或对象。不过需要注意的是,此方法无法检查该对象的原型链中是否具有该属性,该属性必须是对象本身的一个成员。
<span style="font-family:Microsoft YaHei;">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";</span>