我正在从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
}
Run Code Online (Sandbox Code Playgroud)
这是它应该循环的对象数组:
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"]
}
];
Run Code Online (Sandbox Code Playgroud)
编辑: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
}
Run Code Online (Sandbox Code Playgroud)
您必须将变量的值作为键返回
return contact[i][prop];
Run Code Online (Sandbox Code Playgroud)
通过执行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
}
Run Code Online (Sandbox Code Playgroud)
此外,您将在第一次迭代时返回每个案例.即使名称稍后在数组上也是如此.我们试试吧
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";
}
Run Code Online (Sandbox Code Playgroud)
我的方式(没有测试)
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"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
246 次 |
| 最近记录: |