junky
junky

Reputation: 1478

Error tyring to use loop in javascript, getting "undefined"

I am trying to print out the names of each person in the loop.
However I get undefined 3 times. How can I fix that?

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

family = {};
family[0] = new Person("mark", 3);
family[1] = new Person("tom", 12);
family[2] = new Person("michael", 45);
family[3] = new Person("joe", 65);

for (i=0; i<4; i++) {
  member = family[i];    
  console.log(member.name); 
  }

Upvotes: 0

Views: 64

Answers (3)

Devin M
Devin M

Reputation: 9752

You want to use this instead of self otherwise the objects wont construct correctly. Also you can use push to add elements to an array instead of using the indexes.

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

family = [];
family.push(new Person("John", 40));
family.push(new Person("Paul", 69));
family.push(new Person("George", 58));
family.push(new Person("Ringo", 71));

for (var i=0; i < family.length; i++) {
  console.log(family[i].name);
}

Upvotes: 1

James M
James M

Reputation: 16718

There's no self keyword in JavaScript. You meant this:

this.name = name;
this.age = age;

Upvotes: 2

hvgotcodes
hvgotcodes

Reputation: 120178

You should use this, not self in your Person Object.

As a note, you probably want var in front of family, i, and member. (unless you want those to be global)

Also, be aware you are setting up an object literal, which is working as a hash, not an array. Don't know what you intended.

Upvotes: 1

Related Questions