怀疑与查询练习

时间:2017-08-06 06:02:58

标签: javascript if-statement

当我在freeCodeCamp中做一些js练习时,我遇到了这个挑战。 我们的联系人列表中有一组代表不同人的对象。

为您编写了一个以firstName和一个属性(prop)作为参数的lookUpProfile函数。

该函数应检查firstName是否为实际联系人的firstName,并且给定属性(prop)是该联系人的属性。

如果两者都为真,则返回"值"该财产。

如果firstName与任何联系人不对应,则返回"没有此类联系人"

如果道具与任何有效的属性不对应,则返回"没有这样的属性"  这是 已完成的 代码:

 //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(myName, myProp){
// Only change code below this line
  for (var i = 0; i < contacts.length; i++){

    if (contacts[i].firstName === myName){

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

  } else {
        return "No such contact";}
  }

// Only change code above this line
}


// Change these values to test your function
lookUpProfile("Kristian", "lastName"); 

但它只会返回&#34;没有这样的联系&#34;从我的猜测来看,第一个如果不评估为真。但是,即使网站的答案也是一样的。第一次比较真的有什么问题吗?它是什么?

1 个答案:

答案 0 :(得分:0)

只有一个小问题,您只是比较第一个联系人,如果值不匹配则返回“没有这样的联系人”。相反,您应该等待for循环与所有联系人进行比较,如果找不到匹配则返回“无此联系”。

在下面的代码中,我添加了一个日志语句以及修复程序,以显示在返回结果之前它与所有四个联系人的比较。当然,如果找到匹配项,程序将立即返回。

//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(myName, myProp) {
  var matchingContact = null;

  for (var i = 0; i < contacts.length; i++) {
    console.log("Comparing: " + contacts[i].firstName + " with " + myName);
    
    if (contacts[i].firstName === myName) {
      matchingContact = contacts[i];

      if (contacts[i].hasOwnProperty(myProp)) {
        return contacts[i][myProp];
      } else {
        return "No such property";
      }
    } 
  }
  
  return "No such contact";
}


// Change these values to test your function
console.log(lookUpProfile("Kristian", "lastName"));
console.log(lookUpProfile("Jake", "lastName"));
console.log(lookUpProfile("Kristian", "noSuchProp"));