7.search for a friend


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-3bmfN/0/7?curriculum_id=506324b3a7dffd00020bf661#


I think my code gives me too many outputs. What's the problem?


var friends = new Object();
friends.bill = new Object();
friends.steve = new Object();

friends.bill = {
    firstName: "Bill",
    lastName: "Gates",
    number: "(206) 555-5555",
    address: ['One Microsoft Way','Redmond','WA','98052']
};

friends.steve = {
    firstName: "Steve",
    lastName: "Jobs",
    number: "(407) 555-5555",
    address: ['1 Infinite Loop','Cupertino','CA','95014']
};

var list = function (obj) {
    for (var loop in obj) {
        console.log(loop)
    }
};

var search = function (name) {
    for (var loop in friends) {
        if (friends[loop].firstName === name) {
            console.log(friends[loop]);
            return friends[loop];
        }
    }
};

list(friends);
search("Bill");

Here is console output:

bill
steve
{ firstName: 'Bill',
  lastName: 'Gates',
  number: '(206) 555-5555',
  address: [ 'One Microsoft Way', 'Redmond', 'WA', '98052' ] }
{ firstName: 'Steve',
  lastName: 'Jobs',
  number: '(407) 555-5555',
  address: [ '1 Infinite Loop', 'Cupertino', 'CA', '95014' ] }
{ firstName: 'Steve',
  lastName: 'Jobs',
  number: '(407) 555-5555',
  address: [ '1 Infinite Loop', 'Cupertino', 'CA', '95014' ] }
{ firstName: 'Bill',
  lastName: 'Gates',
  number: '(206) 555-5555',
  address: [ 'One Microsoft Way', 'Redmond', 'WA', '98052' ] }
{"firstName":"Bill","lastName":"Gates","number":"(206) 555-5555","address":["One Microsoft Way","Redmond","WA","98052"]}

#2

Hmm, seems problem doesn't exist. In the next section code outputs normally.
Anyway, if you have any comment to my code, I'll be happy to correct it!


#3

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