为什么代码为某些对象属性给出错误?

时间:2018-12-22 12:41:00

标签: javascript loops

为您预先编写了一个以名称和属性(prop)为参数的lookUpProfile函数。

该函数应检查name是否是实际联系人的名字,并且给定属性(prop)是该联系人的属性。

如果两者都为true,则返回该属性的“值”。

如果姓名与任何联系人都不对应,则返回“没有此类联系人”

如果prop不符合与姓名匹配的联系人的任何有效属性,则返回“无此属性”

//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(name, prop){
// Only change code below this line
 for(var i = 0; i < contacts.length;i++){
  if(name === contacts[i].firstname ){
    if(contacts[i].hasOwnProperty(prop)){
      return contacts[i][prop];
    }else {
      return "No such property";
    }
  }
}
return "No such contact";

// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");

“ Kristian”,“ lastName”应返回“ Vos” “ Sherlock”,“ likes”应返回[“ Ingringing Cases”,“ Violin”] “ Harry”,“ likes”应返回一个数组 “ Akira”,“地址”应返回“无此属性”

1 个答案:

答案 0 :(得分:1)

将此条件if(name === contacts[i].firstname )替换为if(name === contacts[i].firstName )。您错误地使用了firstname而不是firstName

javascript区分大小写,会将firstnamefirstName视为两个不同的变量