7 search for a friend


#1

hey guys,

i honestly dont understand this code especially the for loop..its just confusing and thou am cool to go to the next exercise, i really want to know this. please kindly explain


var friends = {};
friends.steve = {
    firstName: "Steve",
    lastName: "Brown",
    number: "08167626626",
    address: ["cbn estate 1", "satellite town", "lagos"]
    };
friends.bill = {
    firstName: "Bill",
    lastName: "Blue",
    number: "08197926726",
    address: ["cbn estate 3", "satellite town", "lagos"]
    };
friends.mercy = {
    firstName: "Mercy",
    lastName: "Thomas",
    number: "08197820626",
    address: ["cbn estate 2", "satellite town", "lagos"]
    };
    
    var list = function (baby) {
        for (var key in baby) {
            console.log(key);
        }
    };
    
    list(friends);
    
    var search = function (name) {
    for (var search in friends) {
        if (friends[search].firstName === name) {
            console.log(friends[search]);
            return friends[search];
        }
      }
    };
    
    search("Mercy");


#2

Hey there @rheedhar

The purpose of a for loop is to repeat an action a certain amount of times. A for loop (not using arrays or objects) can be pretty simple:

for (var i=0; i<10; i++){
    console.log("I've looped "+i+" times.");
}

This will loop 10 times and tell you it has looped i amount of times, i being the counter.

When using for loops with arrays or objects, you can move through the array until there are no other items. This is useful for getting information on each item in said array or object. This is used in your program. Assuming there is an array with 10 numbers in it, from 1 to 10 that is called numbers...

for (var i in numbers){
    sum=sum+i;
}

This iterates through the array numbers and each time, adds to the previous total, whatever number is next in line. Eventually, sum will equal 55, the equivalent of 1+2+3+4+5+6+7+8+9+10.

"For loops in a nutshell." Any other questions? Post again, and someone will try to help you out.


#3

hey,
thanks for replying... i understand how the for loop works normally but using it with arrays or objects is the problem. i still have some questions.

1 can the i be anything ?
2. i still dont understand the second for loop in the exercise.
3. in your example, if i do
for (var i in numbers) {
console.log(i);
};

does this mean am printing 1 - 10.

thanks in advance....


#4
  1. i can be swapped with anything of your choosing, as long as you change it every time.
  2. What about it is confusing?
  3. Correct.

#5

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