函数返回错误消息不起作用

时间:2017-03-02 21:18:52

标签: javascript arrays function object

我实际上有点问题:我想创建一个在数组中的对象中循环的函数。

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; i < contacts.length; i++) {
        for (var prop1 in contacts[i]) {
            if (contacts[i][prop1] == firstName) {
                if (contacts[i].hasOwnProperty(prop)) {
                    return contacts[i][prop];
                }
            }
         }
     }
 }

 lookUpProfile("Sherlock", "likes");

我想要返回两个错误:&#34;没有这样的联系&#34;和#34;没有这样的类别&#34; (我评论了我放置&#34的部分;返回&#39;没有这样的联系&#39;&#34;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39

1 个答案:

答案 0 :(得分:1)

试试这段代码:

&#13;
&#13;
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) {
  var contact = contacts.find(function(contact) {
    return contact.firstName === firstName;
  });

  if (!contact) {
    return 'No such contact';
  }

  if (!contact.hasOwnProperty(prop)) {
    return 'No such category';
  }

  return contact[prop];
}



console.log(lookUpProfile("Sherlock", "likes"));
&#13;
&#13;
&#13;