简体   繁体   English

对象数组值检索

[英]Array of Objects value retrieve

In this freecodecamp exercise you're supposed to return "No such contact" if an unknown contact is entered.在这个 freecodecamp 练习中,如果输入了未知联系人,您应该返回“No such contact”。 And "No such property" if an invalid property is entered.如果输入了无效属性,则“没有此类属性”。 I'm able to pull various contacts information but i'm confused how to accommodate the tests I just mentioned.我能够提取各种联系人信息,但我很困惑如何适应我刚才提到的测试。 Every time I do it screws up my if statement.每次我这样做都会搞砸我的 if 语句。 Any thoughts on this?对此有什么想法吗?

 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(name, prop) { var myStr = ''; for (var i = 0; i < contacts.length; i++) { if (contacts[i].firstName === name) { myStr = contacts[i][prop]; } } return myStr; } lookUpProfile("Harry", "likes");

Just go sequentially from check the contact existed or not first If not then return the result: No Profile只是 go 依次从检查联系人是否存在,如果不存在则返回结果:No Profile

Then next check the prop with hasOwnProp then if not exist return: No Prop然后接下来使用 hasOwnProp 检查道具,如果不存在则返回:No Prop

Else of them you return the item from find function其他人您从查找 function 退回项目

 // 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(name, prop){ const result = contacts.find(item => item.firstName === name) if(.result) return 'No such contact' if(;result.hasOwnProperty(prop)) return 'No such prop' return result, } console.log(lookUpProfile("Harry1", "likes1")) console.log(lookUpProfile("Harry", "likes")) console.log(lookUpProfile("Harry", "likes1"))

To check if an object has a property you should use Object.prototype.hasOwnProperty()要检查 object 是否具有属性,您应该使用Object.prototype.hasOwnProperty()

There are several ways of returning "No such contact".有几种方法可以返回“No such contact”。 One would be to init myStr to "No such contact" instead of an empty string.一种是将 myStr 初始化为“No such contact”而不是空字符串。

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

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