为什么此函数中的 if 循环返回错误的语句?(来自 fCC 个人资料查找挑战赛)

Why does the if loop in this function return the wrong statement? (from fCC Profile Lookup challenge)

提问人:szayel 提问时间:11/11/2023 更新时间:11/11/2023 访问量:22

问:

我正在做 freeCodeCamp Profile Lookup 挑战,但我对为什么必须在 for 循环之外感到困惑。在我的第一次尝试中,我将其写为第一个 if 语句之后的语句,但这将返回“No such contact”而不是属性的值。return "No such contactelse

我尝试查看有关此挑战的其他线程,我知道它与让 for 循环在返回语句之前运行所有迭代有关,但为什么需要发生这种情况,以及为什么它会导致代码不起作用?

这是我正在谈论的版本(另外,我知道我错过了“没有这样的属性”返回;在这一点上,我还没有达到它):

function lookUpProfile(name,prop) {
  for(let n = 0; n<contacts.length; n++ ){
    if(name == contacts[n].firstName && contacts[n].hasOwnProperty(prop)){
      return contacts[n][prop]
    } else {
      return "No such contact"
    }
  } 
}

当我这样做时,结果是“没有这样的联系”,但没有 else 语句,它返回正确的值,即“Vos”。console.log(lookUpProfile("Kristian", "lastName"))

这是我修复后的正确版本,以及来自站点的完整代码:

// Setup
const 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(name, prop) {
  // Only change code below this line
  let n = 0; // index of contacts array
  for(n = 0; n<contacts.length; n++ ){
    if(name == contacts[n].firstName){
      return contacts[n][prop] || "No such property"
    } 
  } 
  return "No such contact"

  // Only change code above this line
}

lookUpProfile("Akira", "likes");```

javascript for 循环 if 语句

评论


答:

0赞 brk 11/11/2023 #1

这是因为在循环内部,在每次迭代中都会检查,当它不匹配时,它将被阻塞。在 return' 语句中。因此,循环在那里停止执行,并在不进一步迭代的情况下存在函数。forifelseelse block there is

const 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(name, prop) {
  for (let n = 0; n < contacts.length; n++) {
    if (name === contacts[n].firstName && contacts[n].hasOwnProperty(prop)) {
      return contacts[n][prop]
    }
  }

  return "No such contact"

}

console.log(lookUpProfile("Akira", "likes"));
console.log(lookUpProfile("Kristian", "lastName"))