13.27 - Code problem


#1

Hi, I have a little bit of an issue right here. I'm now at: Introduction to Objects I > Loop the Loop
For some reason it isn't printing what I want it to print, which is the family array.

This is the error I get when I run the code:
Oops, try again. It looks like the object at index 0 was not created with the Person constructor


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

// Now we can make an array of people
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);

// loop through our new array
var i;
for (i = 0; i <= family; i++) {
    console.log(family[i]);
}

Weird thing is if I do the following in the for loop:

var i;
for ( i = 0; i < 4; i++) {
    console.log(i);
}

then it is printing: 0123
So I am pretty sure it isn't in the for loop itself, but in selecting the array or something.

Help is really appreciated!

Thanks in advance,
Brent


#2

Check your condition of for loop, we loop over certain amount of length (say a definite number)?

Note:
Take a look at instructions & Theory again


#3

lol you're right, when you said (A definite number?) I was like family.length and it works now totally fine! You're amazing :smiley:


#4

family.length is preferable to hard-coding a number such as 4, although it works for short arrays where you can easily count the length. In your original code you simply had a typo, "i <= family", but it should be "i < family.length".


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.