10

I have code like this, then I was confused on how to loop the array family to print each member under person.

function Person(name,age){
    this.name = name;
    this.age = age;
}


var family = [];
family[0] = new Person("alice",40);
family[1] = new Person("bob",42);
family[2] = new Person("michelle",8);
family[3] = new Person("timmy",6);
Cœur
  • 34,719
  • 24
  • 185
  • 251
davinceleecode
  • 716
  • 2
  • 10
  • 29
  • So you're asking how objects _work_ ? Heres a hint: look up the `for` loop, then look up `javascript objects`. If you cant figure it out then take a tutorial or two. This isn't even a question... How about `for(person in family){ alert(family[person].name); }`... See how simple? – somethinghere Feb 25 '15 at 14:40

1 Answers1

3

here is a JsFiddle

is that what you need ?

for (var key in family) {
   var obj = family[key];
   for (var prop in obj) {
      alert(prop + " = " + obj[prop]);
   }
}

Here is the way to access the properties directly and not with a loop jsFIddle (Method 2, uncomment)

Romain Derie
  • 506
  • 6
  • 17
  • 2
    I try also doing a different way by my self like this code basing on your code. for(var name = 0; name < family.length;name++) { console.log('Name: ' + family[name]["name"] + ' Age: ' + family[name]["age"]); } – davinceleecode Feb 25 '15 at 16:00