2 回答
TA贡献1803条经验 获得超6个赞
我认为这是让你感到困惑的 for 循环。问题要求我们检查是否name does not correspond to any contacts then return "No such contact"。因此,在您的回答中,您一到达第一个无效联系人就
返回,这不是想要的问题。 您应该将自己排除在 for 循环之外,作为最终的包罗万象。else if (contacts[i]===name) {return "No such property";}
return "No such contact"
除此之外,当您需要检查对象中是否存在某个属性时,您可以使用Object.hasOwnProperty(propertyName). contacts[i]inelse if (contacts[i]===name) {return "No such property";}会给你联系人中的实际对象,它永远不会匹配name.
您将需要获得name带括号或点的注释。例子:
contacts[0] is equal to
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
}
contacts[0].firstName is equal to "Akira"
contacts[0]["firstName"] is equal to "Akira"
// Setup
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(name, prop) {
// Only change code below this line
for (let i = 0; i < contacts.length; i++) {
const contact = contacts[i];
if (contact.firstName === name && contact.hasOwnProperty(prop)) {
return contact[prop];
} else if (contact.firstName === name && !contact.hasOwnProperty(prop)) {
return "No such property";
}
}
return "No such contact";
// Only change code above this line
}
lookUpProfile("Akira", "likes");
TA贡献1869条经验 获得超4个赞
先找个人资料,再找房产
function lookUpProfile(name, prop) {
const profile = contacts.find((contact) => contact.firstName === name)
if (!profile) return "No such contact"
const property = profile[prop]
if (!property) return "No such property"
return property
}
// Setup
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(name, prop) {
// Only change code below this line
const profile = contacts.find((contact) => contact.firstName === name)
if (!profile) return "No such contact"
const property = profile[prop]
if (!property) return "No such property"
return property
// Only change code above this line
}
console.log(lookUpProfile("Akira", "likes"))
console.log(lookUpProfile("Bkira", "likes"))
console.log(lookUpProfile("Akira", "nikes"))
添加回答
举报