Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript using constructor inside in Array [duplicate]

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);
like image 978
davinceleecode Avatar asked Feb 25 '15 14:02

davinceleecode


1 Answers

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)

like image 107
Romain Derie Avatar answered Oct 23 '22 11:10

Romain Derie