1.我们有一个对象数组,里面存储着通讯录。
函数 lookUp 有两个参数: firstName 和 prop 。
函数将会检查通讯录是否存在 firstName 值 和 prop 属性。
如果它们都存在,函数返回prop属性对应的值。
如果firstName 值不存在,返回 "No such contact"。
如果prop 属性不存在,返回 "No such property"。
2.第一段代码是错误的但是不知道错在哪里
for(var i = 0; i < contacts.length; i++){
for(var j = 0; j < contacts[i].length; j++){
if(contacts[i][j] == firstName && contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}else if(!contacts[k].hasOwnProperty(prop)){
return "No such property";
}else{
return "No such contact";
}
}
}
3.这是对的代码,但是我觉得和上面的没有什么区别。。除了最后一句return放到了循环外。
for(var k in contacts){
for(var i in contacts[k]){
if(contacts[k][i] === firstName && contacts[k].hasOwnProperty(prop)){
return contacts[k][prop];
}else if(!contacts[k].hasOwnProperty(prop)){
return "No such property";
}
}
}
return "No such contact";
4.这也是对的代码,但是不太懂index的作用
function lookUp(firstName, prop){
// Only change code below this line
var index;
for(var i=0;i<contacts.length;i++){
if(contacts[i].firstName === firstName){
index = i;
break;
}
}
if(index<contacts.length){
if(contacts[index].hasOwnProperty(prop)){
return contacts[index][prop];
}else{
return "No such property";
}
}
else{
return "No such contact";
}
第一个写法的问题,对象不能用
for(var j = 0; j < contacts[i].length; j++)
遍历其属性。所以结果不正确