Contact list? Cant understand the for/in loop


#1

var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number:12344566,
address:["ksnd,nm","ms,dbk",28972]
};
friends.steve = {
firstName: "Steve",
lastName: "Jobs",
number:18617652,
address:[8176518,187618,17615]
};
var list = function(Obj){
for (var anything in Obj){
console.log(anything);
}
};
var search = function(name){
for (var anything in friends){
if (friends[anything].firstName = name){
console.log(friends[anything]);
return friends[anything]
}
}
};
list(friends);
search("bill");

This is my code. I cant understand the for/in loop. How does it work and what does it do? And i also do not understand the list function and why is it necessary.


#2

@ajaxjumper52610 the list function is just there to display all of the properties attached to that object. the for/in loop is used to loop through all of the properties that an object has. you can use it to search for a specific property or value, or to display a specific property or value. the counter variable -- anything in your loop -- takes on each subsequent property of the object mentioned, each time the loop is executed, until it gets to the last property of that object, then the loop quits.


#3

The list() function has one purpose... To list the primary key names of an object.

var list = function (object) {
    for (var key in object) {
        console.log(key);
    }
};

Given an object,

var friends = {
    bill: {},
    steve: {}
};

list(friends);
/*
    bill
    steve
*/

A for..in statement treats a JavaScript object as an Associative Array with string index and associated value pairing. The iterator variable is dynamic, taking on one key name in each iteration.

In the above, key was first 'bill' then 'steve'.

Your search() function looks correct except for two things:

  1. ... = name should be ... === name
  2. The call should search for a data value, not a key... search("Bill");