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);
1
  • 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? Commented Feb 25, 2015 at 14:40

1 Answer 1

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)

1
  • 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"]); } Commented Feb 25, 2015 at 16:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.