我试图获得联系人的数据时,名称实际上存在于我的数组,当它不"没有这样的联系人"提示符,就像这样,它工作了,我得到"Vos">
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) {
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === name) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property"
}
}
}
}
lookUpProfile("Kristian", "lastName");
但是当我添加了额外的东西,如果它不再识别这个名字,我就会得到&;No such contact&;我想是一些非常简单和明显的东西,但我就是不明白为什么
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) {
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName === name) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property"
}
} else if (contacts[i].firstName[name] === undefined) {
return "No such contact"
}
}
}
lookUpProfile("Kristian", "lastName");
问题是您在第二个代码片段中的第一次迭代之后从循环返回。因此,您只检查第一个项目,然后返回"No such contact"。看起来你只有在没有找到联系人的情况下才想在最后回来。我添加了一个控制台日志,显示循环经过了多少次迭代,这应该有助于故障排除。
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) {
for (var i = 0; i < contacts.length; i++) {
console.log('Loop: ' + i);
if (contacts[i].firstName === name) {
if (contacts[i].hasOwnProperty(prop)) {
return contacts[i][prop];
} else {
return "No such property"
}
} else if (contacts[i].firstName[name] === undefined) {
return "No such contact"
}
}
}
console.log(lookUpProfile("Kristian", "lastName"));