gpt4 book ai didi

javascript - 在 if 条件语句中访问 Javascript 对象,可以做到吗?

转载 作者:行者123 更新时间:2023-11-29 16:49:17 25 4
gpt4 key购买 nike

这是我在免费代码训练营挑战“Profile Lookup”中的代码,我被这段代码卡住了,我的问题是 if 条件,如何让测试用例进入我的第一个 if 条件?

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 ( var i = 0; i < contacts.length; i++) {
if ( contacts[i].firstName === firstName && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
}
else if (firstName !== contacts[i].firstName) {
return "No such contact";
}
else if (contacts[i].hasOwnProperty(prop) === false) {
return "No such property";
}
}
}

lookUpProfile("Harry", "likes");

我应该得到的是“likes”的值,也就是["Hogwarts", "Magic", "Hagrid"],要做到这一点,它应该进入第一个if条件,并且有问题。

最佳答案

你的问题是你提前回来了。无论如何,如果满足任何条件,您总是会返回 contacts 集合的第一次迭代。您需要做的是将答案存储在循环外的局部变量中,然后返回该值。这样做可以确保您已经完成所有迭代而不会过早返回。

试试这个:

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) {
var result = undefined;
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === firstName) {
result = contacts[i];
}
}

if (result === undefined) {
return "No such contact";
}
if (result.hasOwnProperty(prop) === false) {
return "No such property";
}

return result[prop];
}

console.log(lookUpProfile("Harry", "likes"));

一种更实用和惯用的方法是使用数组方法,例如 filter

关于javascript - 在 if 条件语句中访问 Javascript 对象,可以做到吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37800895/

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