基本配置文件查找始终返回未找到联系人

时间:2017-07-15 12:23:56

标签: javascript arrays

所以我最近开始使用freecodecamp上的教程学习Javascript,而且这个挑战我已经坚持了好几个小时了。

该函数始终返回“未找到联系人”,我不明白为什么。如果有人向我解释并更正我的代码,我将不胜感激。

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(firstName, prop) {

  for (var i=0; contacts.length>i; i++) {

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

lookUpProfile("Akira", "lastName");

3 个答案:

答案 0 :(得分:1)

最好使用Array.prototype.find()

function findByProp(list, val, prop) {
  let found = list.find(el => el[prop] === val);
  return found ? found[prop] : "No contact found";
}



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 findByProp(list, val, prop) {
  let found = list.find(el => el[prop] === val);
  return found ? found[prop] : "No contact found";
}

console.log(findByProp(contacts, "Akira", "firstName"));
console.log(findByProp(contacts, "foo", "firstName"));




答案 1 :(得分:0)

试试这个

<强>解释

  1. 错误错误更改为contacts[i]['firstName']而不是contacts[i][firstName]。您将缺少匹配keyname的{​​{1}}。你的呼唤方式如

    obj所以只有它总是去声明

  2. 使用contacts[i][Akira] == false statement代替obj[key]执行对象键调用方法.Beacuse all is varible not not name of key
  3. 第二个obj.key。你没有提到用该对象检查哪个词
  4. &#13;
    &#13;
    hasownproperty(varible)
    &#13;
    &#13;
    &#13;

答案 2 :(得分:-1)

function lookUpProfile(name, prop) {

    for (let i = 0; i < contacts.length; i++) {

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