gpt4 book ai didi

javascript - hasOwnProperty 未正确返回?

转载 作者:行者123 更新时间:2023-11-28 17:59:23 26 4
gpt4 key购买 nike

为什么此函数返回“No Contact”而不是“Akira”?

function lookUpProfile(firstName, prop){
for(i=0;i<contacts.length;i++){
if(contacts[i].hasOwnProperty.prop){
return firstName;
}
return 'no contact' ;
}
}


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"]
}
];





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

最佳答案

您需要将您的 prop 作为参数传递。

function lookUpProfile(firstName, prop){
for(i=0;i<contacts.length;i++){
if(contacts[i].hasOwnProperty(prop)){
return firstName;
}
return 'no contact' ;
}
}


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"]
}
];





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

关于javascript - hasOwnProperty 未正确返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43856114/

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