【问题标题】:Nested If statements, for loops and else if ordering in Javascript (FreeCodeCamp - lookUpProfile)嵌套的 If 语句、for 循环和 else if 在 Javascript 中排序 (FreeCodeCamp -lookUpProfile)
【发布时间】:2016-05-03 02:35:11
【问题描述】:

我目前正在编写 Free Code Camp 的 Javascript 教程,并且卡在“联系人资料”problem 上。我的一些 if 以及它们的嵌套/排序方式存在问题。我的代码如下。

具体来说,谁能解释当你在 for 循环中有两个嵌套的 if 语句时如何嵌套“else if”语句?看来代码需要先完成迭代,但我不能让我的语法或顺序正确。

function lookUpProfile(firstName, prop){
// Only change code below this line
for(var i = 0; i < contacts.length; i++){
  if(contacts[i].firstName === firstName){
    if(contacts[i].hasOwnProperty(prop)){
     }
  return contacts[i][prop];

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

【问题讨论】:

  • 不幸的是,这并没有做到,但我想通了,现在正在回答我的问题

标签: javascript if-statement for-loop


【解决方案1】:

所以正确的代码如下,我在第一个 if 语句中遇到了问题,而不是使用点表示法,我使用的是“contacts[i][firstName] === firstName”,我认为这导致它不正确评估第一个 if 语句。

如果有人能解释为什么会这样,那就太好了!

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 2017-02-06
    相关资源
    最近更新 更多