gpt4 book ai didi

javascript - 重构查找函数

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

我正在尝试重构此功能,但碰壁了。该函数试图完成的是查找 JSON 对象中是否存在联系人,如果存在,则确定提供的第二个参数是否是指定对象上存在的属性。

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

}

for (var j = 0; j < contacts.length; j++) {
if (contacts[j].firstName !== firstName) {
return "No such contact";
} else if (!contacts[j].hasOwnProperty(!prop)) {
return "No such property" ;
}

}

// Only change code above this line
}

// Change these values to test your function
lookUpProfile("kyle", "lastName");

最佳答案

过滤任何匹配项,如果找到该属性,则返回 true else false

function lookUpProfile(firstName, prop) {
var list = contacts.filter(function (el) {
return el.firstName === firstName;
});
return list.length && list[0][prop] ? true : false;
}

lookUpProfile("kyle", "lastName"); // false
lookUpProfile("Akira", "lastName"); // true
lookUpProfile("Akira", "password"); // false

DEMO

关于javascript - 重构查找函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37221346/

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