0

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); 
  }

3 Answers 3

2

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

this.name = name;
this.age = age;
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I tried that, both []; and also new Array; Still getting the error.
1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.