繁体   English   中英

使用 for 循环和 if 条件查找配置文件

[英]Profile Look Up using for loop and if condition

已经为我预先编写了一个lookUpProfile function,它采用名称和属性(prop)作为arguments。

如果两者都为真,则返回该属性的“值”。

如果姓名不对应任何联系人,则返回字符串 No such contact。

如果 prop 不对应于找到匹配名称的联系人的任何有效属性,则返回字符串 No such property。

如果我使用 && 而不是嵌套的 if 语句,为什么它不起作用

// 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
  for (let i = 0; i <= contacts.length; i++) {
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
      return contacts[i][prop];
    } else return "No such contact";
  }
  return "No such contact";
  // Only change code above this line
}

lookUpProfile("Akira", "likes");



function lookUpProfile(name, prop) {
  for (let x = 0; x < contacts.length; x++) {
    if (contacts[x].firstName === name) {
      if (contacts[x].hasOwnProperty(prop)) {
        return contacts[x][prop];
      } else {
        return "No such property";
      }
    }
  }
  return "No such contact";
}
function lookUpProfile(name, prop) {
  // Only change code below this line
  for (let i = 0; i <= contacts.length; i++) {
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
      return contacts[i][prop];
    } else return "No such contact";
  }
  return "No such contact";
  // Only change code above this line
}

如果 contacts[0] 不是您想要获取的值,则此 function 将始终返回“No such contact”。

下面的代码将起作用。

function lookUpProfile(name, prop) {
  // Only change code below this line
  for (let i = 0; i <= contacts.length; i++) {
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
      return contacts[i][prop];
    } 
  }
  return "No such contact";
  // Only change code above this line
}

问题是这些行

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

您基本上是在说如果给定条件不匹配,则返回 function 并带有'No such contact' 这意味着循环在第一次迭代后停止迭代。 现在由于返回 function 循环结束,这意味着您只检查第一个索引,即[0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM