vendredi 8 juillet 2016

Loops through Array but executes “else” statement even when “if” statement is true (javascript)

In the loop I am not sure if I have made a mistake or bad code. When I run the if statement alone, it works. But when I run it along with the "else if " statement. The if statement fails, the else if statement works, even when the first if statement is true.

//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(firstName, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++) {
  if ( contacts[i].firstName === firstName  &&     contacts[i].hasOwnProperty(prop) ) {
    return contacts[i][prop];


}  else if( contacts[i].firstName !== firstName ) {
  return "No such contact";  
    }
  }
// Only change code above this line
}

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

Aucun commentaire:

Enregistrer un commentaire