trying to use a for loop with if else statement in objects

馋奶兔 提交于 2021-02-05 09:40:29

问题


I'm trying to write a function that will iterate through a variable holding objects. If you pass in a first name that is an object property, you should get true. If not, you should get false. However, no matter what I pass through the function, I always get false. Any help is greatly appreciated.

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:


Think through the logic for a moment: What happens on the first loop? What does the function do in response to the if/else? Right! It returns true or false right away, without looping through the remaining entries at all.

You need to remove the else entirely and move return false to outside the loop:

function attempt(firstName) {
    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].firstName == firstName) {
            return true;
        }
    }
    return false;
}

Side note: Array#some is designed for exactly this use case:

function attempt(firstName) {
    return contacts.some(function(entry) {
        return entry.firstName == firstName;
    });
}


来源:https://stackoverflow.com/questions/41913027/trying-to-use-a-for-loop-with-if-else-statement-in-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!