代码:
<script>
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=0;i<contacts.length;i++){
if(firstName==contacts[i][firstName]){ //为什么这里使用[ ]引用对象属性就会发生错误,但是如果这里改成firstName==contacts[i].firstName;就对了。这是为什么呢?对象属性不是[ ]可以运用于所有. 可以使用的地方吗?谢谢!
if(contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}else{
return "No such contact";
}
}
}
return "No such property";
}
var aa=lookUp("Akira", "likes");
alert(aa);
</script>
<script>
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=0;i<contacts.length;i++){
if(firstName==contacts[i][firstName]){ //为什么这里使用[ ]引用对象属性就会发生错误,但是如果这里改成firstName==contacts[i].firstName;就对了。这是为什么呢?对象属性不是[ ]可以运用于所有. 可以使用的地方吗?谢谢!
if(contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}else{
return "No such contact";
}
}
}
return "No such property";
}
var aa=lookUp("Akira", "likes");
alert(aa);
</script>