Search function


#1

This question is about the review for Address Book.

In the search function below:

var search = function(lastName) {
    var contactsLength = contacts.length;
    for (var i = 0; i < contactsLength; i++) {
        if (lastName = contacts[i].lastName) {
            printPerson(contacts[i]);
            break;
        };
    };
};

We make a search on the lastName. But what if we cannot find anyone matches. I tried to add an else function, but it seemed not right. How can I make it print out "Can't find this person", if we search some one not in the list?

Can anyone help me with this please?


#2

@sanly123654,

var search = function(lastName) {
    var contactsLength = contacts.length;
    var foundContact = false;
    for (var i = 0; i < contactsLength; i++) {
        if (lastName === contacts[i].lastName) {
            printPerson(contacts[i]);
            foundContact = true;
        }
    }
    if ( !foundContact ) {
        console.log( "Can't find "+lastName+" person" );
    }
};

#3

Thanks a lot! That is what I am asking! :slightly_smiling: