Question about contact list lesson


#1

hello
here is my code
friends=new Object();
friends.bill={
firstName:"Bill",
lastName:"belly",
number:123456,
address:['a','b','c']};
friends.steve={
firstName:'Steve',
lastName:'stevens',
number:12345,
address:['a','b','c']
};
function list(name){
for (var name in friends){
console.log(name)
}
}
function search (name){
for (var a in friends){
if (friends[a].firstName===name){
console.log(friends[a]);
return friends[a];
}
}
}

i can't understand the var a part ( var key in the lesson instructions )
this variable is not defined how can the for loop recognize it in friends object and how can check a condition that has undefined variable ??
can anyone explain for me please
thanks


#2

@amired,

T h e - B a s i c s

An object has one or more properties seperated by a comma-,
Each property consists of a property-key and it's associated VALUE

var nyc = {
       fullName: "New York City",
       mayor: "Bill de Blasio",
       population: 8000000,
       boroughs: 5
      };
nyc -object- S p e c i f i e d

The nyc object has 4 properties seperated by a comma-,
- a fullName property with property-key fullName and it's associated string value of "New York City"
- a mayor property with property-key mayor and it's associated string value of "Bill de Blasio"
- a population property with property-key population and it's associated number value 8000000
- a boroughs property with property-key boroughs and it's associated number value 5

for - in - loop - e x p l a i n e d

With the for-in-loop you have a Method
which will iterate over all properties of a given object.
At each iteration it will assign the property-key as a string
to a variable name of your choice.
Thus for (var x in nyc)
will lead to 4 iteration's
iteration-1 var x = "fullName";
iteration-2 var x = "mayor";
iteration-3 var x = "population";
iteration-4 var x = "boroughs";
As they want you to display the property-key and NOT it's associated VALUE
you would use
console.log( x );

If they wanted you to display the associated VALUE of the propery-key you would use
console.log( nyc[x] );


#3

i thought for-in-loop is a conditional statement like if statement the condition must be true to execute the code in {}
so that mean when using for-in-loop i can use variable of my choice and the compiler will assign that variable to each property key in a raw
so the list function is useless right ?!
also i tried the code in other sites' playgrounds and it didn't work ,, do u know why ??
thanks for your answer


#4

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