gpt4 book ai didi

javascript - 在 freecode camp 检查点上查找个人资料

转载 作者:搜寻专家 更新时间:2023-11-01 04:48:23 25 4
gpt4 key购买 nike

<分区>

所以我正在参加 freecodecamp,我正在解决那里的问题,以便与编程保持同步,但我偶然发现了一个障碍,我不太确定哪里出了问题。

所以我有一个名为 contacts 的对象数组,我需要创建一个名为 lookUp(firstName, prop) 的函数。作业的文本是这样的:

The function should check if firstName is an actual contact's firstName and the given property (prop) is a property of that contact.

If both are true, then return the "value" of that property.

If firstName does not correspond to any contacts then return "No such contact"

If prop does not correspond to any valid properties then return "No such property"

代码:

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": ["Intruiging Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
},
];


function lookUp( firstName, prop ){
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";
}
}
}

// Change these values to test your function
lookUp("Kristian", "lastName");

所以我使用 for 循环检查每个对象来遍历数组。在第一个 if 中,我检查该对象的 firstName 属性是否等于函数参数 firstName,如果为真,我检查该对象是否具有属性 prop ,我应该能够归还它。不过好像是

return contacts[i].prop;

不工作,我有点不知道为什么。我敢肯定这是微不足道的事情,但我不明白为什么。当我进入控制台并进行测试时

contacts[0].likes

我取出数组 ["Pizza", "Coding", "Brownie Points"],但在我的 if 中不起作用。我在这里做错了什么?

编辑

好的,我试过了

function lookUp( firstName, prop ){
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";
}
}
}

但我仍然得到同样的错误:\

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com