尝试在对象中使用带有if else语句的for循环

时间:2017-01-28 18:03:21

标签: javascript if-statement for-loop

我正在尝试编写一个函数来迭代保存对象的变量。如果传入的是作为对象属性的名字,则应该成立。如果没有,你应该得到假。但是,无论我通过什么功能,我总是得到假。非常感谢任何帮助。

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;
    }
 }  
}

1 个答案:

答案 0 :(得分:2)

暂时考虑一下逻辑:第一次循环会发生什么?该功能对if / else的响应有何作用?对!它会立即返回truefalse ,而不会循环显示剩余的条目。

您需要完全删除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;
    });
}