No. 8 Victory - extension help


#1


I'm just doing an extension of the Contact List, as suggested.

My code works fine, I'm just wondering if there's a better way to code the last section where it prints out the address. The result isn't formatted like I'd want it to be (i.e how it is in the example!). I'm also not sure on how I can condense it as it seems quite repetitive.

Any tips would be greatly appreciated!

var friends = new Object();
friends.bill = {
    firstName: "Bill",
    lastName: "Hat",
    number: "1234",
    address: ['One Microsoft Way', 'Redmond', 'WA', '98052']
};
friends.steve = {
    firstName: "Steve",
    lastName: "Pat",
    number: "2345",
    address: ['7 Cow Lane', 'Happy Valley', 'SA', '90210']
};
friends.mailan = {
    firstName: "Mai-Lan",
    lastName: "Tran",
    number: "3456",
    address: ['1 Mocalta Street', 'Glengowrie', 'SA', '90211']
};
var list = function (friends) {
    for (var key in friends) {
        console.log(key);
    };
};
var search = function (name) {
    for (var key in friends) {
        if (friends[key].firstName === name) {
            console.log("First Name:" + " " + friends[key].firstName);
            console.log("Last Name:" + " " + friends[key].lastName);
            console.log("Number:" + " " + friends[key].number);
            console.log("Address:" + " " + friends[key].address[0] + ", " + friends[key].address[1] + ", " + friends[key].address[2] + " " + friends[key].address[3]);
            return friends[key];
        };
    };
};
search("Bill");


#2

Caching repeated variables is one way to lessen all the typing.

var search = function (name) {
    var f, s;
    for (var key in friends) {
        f = friends[key];
        s = "";
        if (f.firstName === name) {
            // build an output string
            // log out the string
            return f;
        }
    }
};

Build the output string

            s += "\nFirst Name: " + f.firstName; 
            s += "\nLast Name:  " + f.lastName; 
            s += "\nNumber:     " + f.number; 
            s += "\nAddress:    " + f.address[0]; 
            s += "\n            " + f.address.slice(1).join(", ");
            console.log(s);

Sample output:


First Name: Bill
Last Name:  Hat
Number:     1234
Address:    One Microsoft Way
            Redmond, WA, 98052

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.