我正在从freeCodeCamp做一个名为" Profile Lookup"的挑战。我的问题似乎是我无法返回对象中属性的值。我使用点符号,但也尝试使用括号表示法。
目标是创建一个遍历对象数组contacts
的函数,以查找给定的firstName
是否在所述数组中,以及该对象是否包含给定的prop
。
如果firstName
和prop
都存在,我们必须返回属性的值。
如果找到firstName
但prop
未找到,则我们返回"没有此类属性"。
如果找不到firstName
,我们会返回"没有此类联系"。
这是我的代码:
function lookUpProfile(firstName, prop){
// Only change code below this line
for(var i = 0; i<contacts.length; i++){
if(contacts[i].firstName == firstName){
if(contacts[i].hasOwnProperty(prop))
return contacts.prop;
else
return "No such property";
}
else
return "No such contact";
}
// Only change code above this line
}
这是它应该遍历的对象数组:
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"]
}
];
编辑:当我改为括号表示法然后回到点表示法时,我必须放弃return contacts[i].prop
中的[i]。即使我重新申请它,我也遇到了同样的问题。这是更新的功能:
function lookUpProfile(firstName, prop){
// Only change code below this line
for(var i = 0; i<contacts.length; i++){
if(contacts[i].firstName == firstName){
if(contacts[i].hasOwnProperty(prop))
return contacts[i].prop;
else
return "No such property";
}
else
return "No such contact";
}
// Only change code above this line
}
答案 0 :(得分:5)
您必须将变量的值作为键
返回return contact[i][prop];
通过执行contacts[i].prop
,您将返回名为prop
的属性:contact[i]['prop']
完成功能
function lookUpProfile(firstName, prop){
// Only change code below this line
for(var i = 0; i<contacts.length; i++){
if(contacts[i].firstName == firstName){
if(contacts[i].hasOwnProperty(prop))
return contacts[i][prop];
else
return "No such property";
}
else
return "No such contact";
}
// Only change code above this line
}
此外,您将在第一次迭代时返回每个案例。即使名称稍后在数组上也是如此。我们试试吧
function lookUpProfile(firstName, prop) {
// Try to find the right contact
for(var i = 0; i<contacts.length; i++) {
// Name is found
if(contacts[i].firstName == firstName){
// Return prop if exist, or error message
if(contacts[i].hasOwnProperty(prop))
return contacts[i][prop];
else
return "No such property";
}
}
// No one with this name is found, return error
return "No such contact";
}
我的方式(未经测试)
function lookUpProfile(firstName, prop) {
let contact = null
// Try to find the right contact
contacts.forEach(c => {
if (!contact && c && c.firstName && c.firstName == firstname) {
contact = c
}
})
if (!contact)
return "No such contact";
return contact.hasOwnProperty(prop) ? contact[prop] : "No such property"
}