我有一行代码出现问题,它似乎没有按预期运行:
if (name === contacts[i].firstName && contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
它应该检查name是否与对象的firstName匹配,以及对象是否具有prop属性——如果两者都为true,则返回该属性。然而,当运行测试时,这段代码似乎被跳过了,因为每个结果都给了我"的答案;没有这样的接触";。
// Setup
const 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(name, prop) {
// Only change code below this line
for (let i = 0; i < contacts.length ; i++){
if (name === contacts[i].firstName && contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}else if (name !== contacts[i]["firstName"]){
return "No such contact"
}else if (prop !== contacts[i]["prop"])
return "No such property";
}
// Only change code above this line
}
const search = lookUpProfile("Akira", "likes");
console.log(search);
下面有一个使用嵌套IF语句的解决方案,但我想知道为什么我最初尝试解决它的方法不起作用。
function lookUpProfile(name, prop) {
for (let x = 0; x < contacts.length; x++) {
if (contacts[x].firstName === name) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return "No such property";
}
}
}
return "No such contact";
}
完整的问题可以在这里访问:https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup
// Setup
const 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(name, prop) {
const contact = contacts.find(({ firstName }) => firstName === name);
if (!contact) {
return "No such contact"
}
if (!contact[prop]) {
return "No such property";
}
return contact[prop];
}
const search = lookUpProfile("Akira", "likes");
console.log(search);