【发布时间】:2022-01-13 05:29:50
【问题描述】:
已经为我预先编写了一个将名称和属性 (prop) 作为参数的 lookUpProfile 函数。
如果两者都为真,则返回该属性的“值”。
如果姓名不对应任何联系人,则返回字符串 No such contact。
如果 prop 不对应于找到匹配名称的联系人的任何有效属性,则返回字符串 No such property。
如果我使用 && 而不是嵌套的 if 语句,为什么它不起作用
// 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 (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else return "No such contact";
}
return "No such contact";
// Only change code above this line
}
lookUpProfile("Akira", "likes");
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";
}
【问题讨论】:
标签: javascript arrays loops for-loop if-statement