gpt4 book ai didi

javascript - 循环遍历包含对象的数组以检索属性

转载 作者:行者123 更新时间:2023-11-30 11:57:55 24 4
gpt4 key购买 nike

我正在研究 Free Code Camp 的类(class),并且被困在某个项目上。我不认为我的循环工作正常,因为它没有检索它应该检索的信息。

说明如下:

We have an array of objects representing different people in our contacts lists.

A lookUpProfile function that takes firstName and a property (prop) as arguments has been pre-written for you.

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"

//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 (i = 0; i < contacts.length; i++) {

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

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

不幸的是,我不确定我的问题出在哪里,非常感谢任何帮助。

最佳答案

您的代码有几处不正确。

首先,hasOwnProperty 并不像您认为的那样。继续阅读 the docs on that

此外,Javascript 区分大小写,并将未定义的属性报告为 undefined 类型的值。因此,下面的 if 并没有完全按照您的要求执行,而且不会产生错误。

if (contacts[i].firstname === prop) {
return contacts[i].firstName;
}

请注意第一个名称属性的不同大小写。

例如尝试以下片段:

console.log(typeof {}.doesNotExist);

它将显示为undefined

最后但并非最不重要:学习如何调试可能会比这些答案获益更多 :) 可以通过在代码中的任意位置添加 console.log 调用来完成一些简单的调试。更好的方法是利用浏览器调试,或使用 IDE 进行调试。

关于javascript - 循环遍历包含对象的数组以检索属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37419258/

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