gpt4 book ai didi

javascript - 使用 for 循环 JS 遍历数组

转载 作者:行者123 更新时间:2023-11-30 20:49:59 25 4
gpt4 key购买 nike

我有一个对象数组(联系人),我需要编写一个函数来检查 firstName (函数的第一个参数) 是否是实际联系人的名字并且给定的属性 (prop 是函数的第二个参数) 是该联系人的属性。如果两者都为真,则返回该属性的“值”。

如果 firstName 不对应于任何联系人,则返回 “No such contact”

如果prop 不对应于任何有效的属性,则返回“没有这样的属性”

我知道我需要做什么,我写的 sudo 但是用实际的 JavaScript 写它我遇到了障碍。

下面是我目前写的:

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 value;
for (i = 0; i < 2; i++) {
if (contacts[i].firstName === true && contacts[i].prop === true) {
value = contacts[i].prop;
return value;
}
}
}

最佳答案

一旦找到具有给定 firstName 的联系人,您就可以使用跳出循环,然后检查传递的 prop 值并相应地返回消息。

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

if(!value) {
return 'No such contact';
}

if(!(prop in value)) {
return 'No such property';
}

return value[prop];
}
console.log(lookUpProfile('Sherlock', 'likes'));
console.log(lookUpProfile('Harry', 'friends'));
console.log(lookUpProfile('John', 'likes'));

关于javascript - 使用 for 循环 JS 遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48276847/

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