JavaScript: Profile Lookup

JavaScript: Profile Lookup
0

#1

Hello, I have a small issue when I doing this challenge.
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup

When I write “return contacts[i].prop;” in the for loop of the function named lookUp , it cannot run test successfully.
However,when I write “return contacts[i][prop];”,it is tested successfully.
I want to know the reason why the former can work but the latter can’t.:roll_eyes:
Thank you.:grinning:

//初始化变量
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(contacts[i].firstName===firstName){
      if(contacts[i].hasOwnProperty(prop)){
        return contacts[i].prop;
      }
      else
        return "No such property";
    }
  }
  return "No such contact";
// 请把你的代码写在这条注释以上
}

// 你可以修改这一行来测试你的代码
lookUp("Akira", "likes");


#2

Hi,

It’s because with contacts[i].prop you’re trying to look for a property named ‘prop’, which doesn’t exist. With contacts[i][prop] though, you’re looking for the string in the variable ‘prop’ and appending it to contacts[i].

For example, given a prop ‘firstname’, when you return contacts[i][prop] you’re actually meaning contacts[i].firstname.


#3

Thanks for your answer.I got it.:smiley::smiley: