mercredi 3 avril 2019

If I don't nest the if/else statements, the code doesn't work. Why do I have to nest?

overview

I am learning JavaScript and have an exercise that combines accessing object properties, loops, and if/else statements.

My code doesn't work. The solution (which works) nests the if/else statements, but otherwise seems to be the same code. I don't understand the difference.

exercise instructions

  • The function should check if name is an actual contact's firstName and the given property (prop) is a property of that contact.

  • If both are true, then return the "value" of that property.

  • If name does not correspond to any contacts then return "No such contact"

  • If prop does not correspond to any valid properties of a contact found to match name then return "No such property"

the given array

 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"]
      }
    ];

my code

(which doesn't work)


function lookUpProfile(name, prop){

for (var i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
        return contacts[i][prop];
    } else if (contacts[i].firstName !== name) {
        return "No such contact";
    } else {
        return "No such property";
    }
}

lookUpProfile("Sherlock", "likes"); 
//should return ["Intriguing Cases", "Violin"]


exercise solution

(which does work)

for (var x = 0; x < contacts.length; x++){
    if (contacts[x].firstName === name) {
        if (contacts[x].hasOwnProperty(prop)) {
            return contacts[x][prop];
        } else {
            return "No such property";
        }
    }
}
return "No such contact";

lookUpProfile("Sherlock", "likes"); 
//returns ["Intriguing Cases", "Violin"]


why?

I expected that the two solutions would both work, but mine does not. Why?

Aucun commentaire:

Enregistrer un commentaire