gpt4 book ai didi

javascript - 根据数组检查输入 - Javascript

转载 作者:行者123 更新时间:2023-11-28 05:13:44 27 4
gpt4 key购买 nike

我是全新的,所以请原谅任何失礼。我寻找解决方案,但找不到任何可以回答我的问题的内容,或者至少找不到任何我能理解的内容。

所以这里是:我想迭代此数组中的每个对象,并检查firstName(在本例中为“Akira”)是否与“contacts”数组中的任何firstName 匹配。在这个阶段,我只想返回对象的索引号(如果可能的话)。如果没有,请告诉我如何以最基本的、5 年前的方式做到这一点。谢谢!

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

lookUpProfile("Akira", "likes");

最佳答案

您的代码有一个错误,您的联系人变量没有关闭“]”,访问对象属性时也使用代码contacts[i][“firstname”]

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 ret = -1;
for (var i = 0; i < contacts.length; i++) {
if (contacts[i]["firstName"] == firstName){
ret = i;
}
}
console.log(ret);
}


lookUpProfile("Akira", "likes");

关于javascript - 根据数组检查输入 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157979/

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