我正在尝试编写一个函数来迭代保存对象的变量。如果传入的是作为对象属性的名字,则应该成立。如果没有,你应该得到假。但是,无论我通过什么功能,我总是得到假。非常感谢任何帮助。
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 attempt(firstName){
for(var i = 0;i < contacts.length; i++){
if(contacts[i].firstName==firstName){
return true;
} else {
return false;
}
}
}
答案 0 :(得分:2)
暂时考虑一下逻辑:第一次循环会发生什么?该功能对if
/ else
的响应有何作用?对!它会立即返回true
或false
,而不会循环显示剩余的条目。
您需要完全删除else
并将return false
移到外面循环:
function attempt(firstName) {
for (var i = 0; i < contacts.length; i++) {
if (contacts[i].firstName == firstName) {
return true;
}
}
return false;
}
附注:Array#some
专为此用例而设计:
function attempt(firstName) {
return contacts.some(function(entry) {
return entry.firstName == firstName;
});
}