Reputation: 71
I'm trying to create a object using my constructor Person, but it doesn't work when I initialize the object directly in the array that uses 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);
}
But it just prints undefined
four times.
I gotta use this 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);
So it prints alice
, bob
, michelle
, timmy
.
What am I doing wrong?
Upvotes: 1
Views: 1263
Reputation: 53958
You could just use this:
var family = [
new Person("alice", 40),
new Person("bob", 42),
new Person("michelle", 8),
new Person("timmy", 6)
];
There isn't any need of enclosing each Person
in brackets.
Now you can loop through the items of your array like below:
for (var index=0; index<family.length; index++) {
console.log(family[index].name);
}
I didn't use the for..in
since this exists for another reason:
The for..in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
For more detais about for...in
, please have a look here.
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 index=0; index<family.length; index++) {
document.write(family[index].name);
document.write("</br>");
}
Upvotes: 2
Reputation: 104775
You're actually creating a 2D array - I think you only want a regular array, then use a regular for
loop to iterate:
var family = [
new Person("alice", 40), //omit the inner arrays, etc./.
];
for (var i = 0; i < family.length; i++) {
//check em out
console.log(family[i].name);
}
Upvotes: 1