【问题标题】:Can I use a for loop with if statement in place of .hasOwnProperty()我可以使用带有 if 语句的 for 循环代替 .hasOwnProperty()
【发布时间】:2018-06-18 23:43:02
【问题描述】:

我正在通过 freeCodeCamp javascript 工作,但由于我忘记了 .hasOwnProperty() 函数而陷入了“配置文件查找”练习,但我仍然不确定为什么我的原始函数不起作用。我将保留给定数组的一部分以供参考。

//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    };


function lookUpProfile(name, prop){
// Only change code below this line
for(let x in contacts){
  if(name === contacts[x].firstName){
    for(let y in contacts[x]){
      if(prop === y){
        return contacts[x][prop]; 
      } else {return "No such property";}
    }
  } 
 } return "No such contact";
// Only change code above this line
}

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

当我遗漏了我的

else {return "No such property";}

行它可以工作,但无论“prop”输入是什么,否则只会返回“没有这样的属性”。

【问题讨论】:

    标签: javascript for-loop if-statement hasownproperty


    【解决方案1】:

    在您的代码中:

    for(let y in contacts[x]){
      if(prop === y){
        return contacts[x][prop]; 
      } else {return "No such property";}
    }
    

    如果proplikes,例如,第一次循环y 可能等于firstNameif ("likes" === "firstName") 是假的,所以我们return "No such property";

    正如您通过删除else 所发现的那样,您要做的是测试每个键,然后在结束时返回“No such property”:

    for(let y in contacts[x]){
      if(prop === y){
        return contacts[x][prop]; 
      }
    }
    return "No such property";
    

    顺便说一句,请使用更多的空白 - 将内容塞到一行中更难阅读。

    【讨论】:

    • 谢谢!那讲得通。很抱歉把这些东西混在一起了,我对编码很陌生,没有得到太多关于风格的反馈:)
    【解决方案2】:

    您的问题是循环中的 if else 语句:

    if(prop === y){
      return contacts[x][prop]; 
    } else {
      return "No such property";
    }
    

    根据您的代码,您只检查联系人对象的第一个属性,因为如果当前检查的属性与正在查找的属性不匹配,则 if else 语句不返回任何属性。这种情况使它不会检查其余属性,而只检查第一个属性(无论它是否正确)

    要解决此问题,请将您的 return 语句移到用于检查属性的循环的末尾:

    for(let x in contacts){
      if(name === contacts[x].firstName){
        for(let y in contacts[x]){
          if(prop === y) return contacts[x][prop]; 
        }
        return "No such property";
      }
    }
    

    这样,如果您完成循环并且仍然没有找到有效的属性,它将正确返回“没有这样的属性”消息,反之亦然,如果您找到了正确的属性,它将返回属性值

    【讨论】:

      【解决方案3】:

      只需将内部循环中 if 条件的 else 部分移出该循环即可。因为,代码执行是在比较第一个属性之后立即返回的。

      【讨论】:

        猜你喜欢
        • 2020-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-06
        • 2019-02-25
        • 2014-03-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多