I am attempting to create an object using my Person constructor. However, I am encountering issues when I try to initialize the object directly in the array using literal notation.
function Person(name, age) {
this.name = name;
this.age = age;
}
var family = [
[new Person("alice", 40)],
[new Person("bob", 42)],
[new Person("michelle", 8)],
[new Person("timmy", 6)]
];
for (var person in family) {
console.log(family[person].name);
}
Unfortunately, it only displays undefined
four times.
To resolve this issue, I must utilize the following notation:
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);
Upon doing so, I successfully print out alice
, bob
, michelle
, and timmy
.
Can someone please point out what mistake I am making?