【问题标题】:Loops through Array but executes “else” statement even when “if” statement is true (javascript)循环遍历数组,但即使“if”语句为真(javascript)也执行“else”语句
【发布时间】:2016-07-08 10:18:31
【问题描述】:

在循环中我不确定我是否犯了错误或错误的代码。当我单独运行 if 语句时,它可以工作。但是当我将它与“else if”语句一起运行时。 if 语句失败,else if 语句有效,即使第一个 if 语句为真。

https://www.freecodecamp.com/challenges/profile-lookup

//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");

【问题讨论】:

    标签: javascript loops object if-statement


    【解决方案1】:

    将“没有此类联系人”回复移到循环之外:

    function lookUpProfile(firstName, prop) {
      var match = false;
      for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].firstName === firstName) {
          match = true;
          var valid = contacts[i].hasOwnProperty(prop);
        }
        if (match && valid) {
          return contacts[i][prop];
        }
        if (match && !valid) {
          return "No such property";
        }
      }
      return "No such contact";  
    }
    

    假设:每个人都存储在一张卡片中。

    此代码遍历所有联系人,当当前联系人符合条件时,立即返回。当循环结束时,表示没有匹配的联系人,所以返回相应的回复。

    我更喜欢这种没有嵌套if 的编码方式,但你可以像这样重写内部for 代码:

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

    【讨论】:

    • 请说明您所做的更改。提供工作代码还不够好
    • 如果我必须添加另外两个带条件的 else 语句怎么办?
    • 你的意思是什么条件?
    【解决方案2】:

    @Max 的替代答案:

    想法是有一个将被返回的变量。现在在每种情况下,您只需要设置这个变量值。这将使您能够添加额外的逻辑,例如getContactmassageContact,如果存在重复值,则合并它们或获取特定值等。

    function lookUpProfile(firstName, prop) {
      var match = undefined;
      // Only change code below this line
      for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop)) {
          match = contacts[i][prop];
          break;
        }
      }
      // Do extra stuff here
      return match ? match : "No such contact"
    }
    

    备用array.find。也可以关注array.filter

    Array.find

    function lookUpProfile(firstName, prop){
      var o = contacts.find(function(c){ return c.firstName === firstName; });
      if(o && o.hasOwnProperty(prop)) return o[prop];
      else if(o && !o.hasOwnProperty(prop)) return "No such property";
      else return "No such contact";
    }
    

    参考资料:

    注意:使用前请检查它们的兼容性。

    【讨论】:

    • @Downvoter,请评论答案中缺少的内容。
    • 哈哈!没关系。算了。
    【解决方案3】:

    Max Zuber 是对的,您的代码如下所示:

    With If else statement:
    for (var i = 0; i < contacts.length; i++) {
    
        // if this true, the inside code block will be executed. 
        // You have return statement so, the loop stops and return the data. 
        if ( contacts[i].firstName === firstName  &&       contacts[i].hasOwnProperty(prop) ) {
    
            return contacts[i][prop];
    
        // if above fails, it will check this condition. 
        // If this true(which on   your design is always true) the inside code block is executed. 
        // You have return statement so the loop stops and return the message. 
        }  else if( contacts[i].firstName !== firstName ) {
         return "No such contact";  
          }
    }
    
    With If statement alone:
    for (var i = 0; i < contacts.length; i++) {
    
        // If this true, stop the loop and return the data. 
        // else, loop continue until no data to be check. 
        if ( contacts[i].firstName === firstName  &&     contacts[i].hasOwnProperty(prop) ) {
    
          return contacts[i][prop];
          } 
    }
    
    // This will only be executed if the above if statement fails. 
    return "No such contact";  
    

    注意: 当函数命中 return 语句时,即使有数据等待检查 if else 语句发生了什么,它也会停止执行并传递 return 语句。

    【讨论】: