samedi 6 juillet 2019

If-else inside a for loop not working - Javascript

I have an array "contacts" with a few properties. My function uses a for to check if the firstName property of each contact matches the name parameter of my function, if it does, it checks if such contact has a property that matches the prop parameter (an if inside the previous if). Both "ifs" have corresponding "elses": "no such property", "not such contact".

Code is very simple actually:

var contacts = [
  {
    "firstName": "Akira",
    "lastName": "Laine",
    "number": "0543236543",
    "likes": ["Pizza", "Coding", "Brownie Points"]
  },
  {
    "firstName": "Harry",
    "lastName": "Potter",
    "number": "0994372684",
    "likes": ["Hogwarts", "Magic", "Hagrid"]
  },
  {
    "firstName": "Kristian",
    "lastName": "Vos",
    "number": "unknown",
    "likes": ["JavaScript", "Gaming", "Foxes"]
  }
];


function lookUpProfile(name, prop) {

  for (var i = 0; i < contacts.length; i++) {

    if (contacts[i].firstName === name) {

      if (contacts[i].hasOwnProperty(prop)) {
        return contacts[i][prop];
      }
      else {
        return "No such property";
      }
    }
    else {
      return "No such contact";}
  }  
}

console.log(lookUpProfile("Harry", "likes"));

Following lines work perfectly:

console.log(lookUpProfile("Akira", "likes"));
console.log(lookUpProfile("Akira", "lala"));

Now, If I put any other firsNames of the rest of the elements:

console.log(lookUpProfile("Harry", "likes"));
console.log(lookUpProfile("Kristian", "likes"));

it returns "No such contact".... :/

Aucun commentaire:

Enregistrer un commentaire