Why my loop doesn't run

时间:2016-07-11 21:04:41

标签: javascript arrays loops object for-loop

I am stuck at this challenge in freecodecamp Profile Lookup and here is my code, i don't understand why my loop isn't running, it checks only the first element contacts[0], why i doesn't get incremented ?

function lookUpProfile(firstName, prop){

 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";
    }
    else if (contacts[i].prop!==prop){
      return "No such property";
    }


  }


}

2 个答案:

答案 0 :(得分:1)

You need to remove the else if conditions as it will always return if the first contact in the array does not match the first name.

function lookUpProfile(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 "Contact found but the property " + prop + " does not exist.";
    }
  }
  return "No contact found.";
}

答案 1 :(得分:0)

It should be something more like this:

function lookUpProfile(firstName, prop){

    for(var i=0;i<contacts.length;i++){
      if(contacts[i].firstName===firstName && contacts[i].hasOwnProperty(prop)){
        return contacts[i][prop];
      }
    }

    return "No such contact and property";
}

Otherwise you are returning after the first loop no matter what. This way the method will loop through every record and only return the error message if it doesn't match.