简体   繁体   English

Javascript 配置文件查找功能

[英]Javascript Profile Lookup function

Here is what I want to achieve:这是我想要实现的目标:

*The function should check if firstName is an actual contact's firstName and the given property (prop) is a property of that contact. *该函数应该检查 firstName 是否是实际联系人的 firstName 并且给定的属性 (prop) 是该联系人的属性。

If both are true, then return the "value" of that property.如果两者都为真,则返回该属性的“值”。

If firstName does not correspond to any contacts then return "No such contact"如果 firstName 不对应任何联系人,则返回“No such contact”

If prop does not correspond to any valid properties then return "No such property"*如果 prop 不对应任何有效属性,则返回“无此类属性”*

My code:我的代码:

//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(firstName, prop){
// Only change code below this line
  for (var i = 0; i<prop.length; i++){
if(contacts.hasOwnProperty(firstName)=== true && contacts.hasOwnProperty(prop)=== true){

  return firstName[i].prop;
}
  else if(firstName !==firstName[i].prop)  {
    return "No such contact";
  }
   else if(prop !== "prop"){
     return "No such property";
   }
  }
// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");

You can use Array.prototype.find to filter out the contact with the firstName - see demo below:您可以使用Array.prototype.find过滤掉带有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(firstName, prop) { var found = contacts.find(function(e){ return e.firstName === firstName; }); if(!found) { return "No such contact"; } else { if(prop in found) { return found[prop]; } else { return "No such property"; } } } // Change these values to test your function var result = lookUpProfile("Akira", "likes"); console.log(result);

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

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