27. Loop the Loop


#1

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

var family = new Array();

var family[0] = new Person("alice", 40);
var family[1] = new Person("bob", 42);
var family[2] = new Person("michelle", 8);
var family[3] = new Person("timmy", 6);

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

SyntaxError: Unexpected token '['. Expected ';' after var declaration.

please help me :smile:


#2

Hello coderockstar50326,
remember that a for loop looks something like this:

for ( i = 0; i < X; i++){
do something!
};

where X is the maximum number which in this case represents the length of the family array

I hope this helped you :relaxed:


#3

wow, somehow my code wasn't copied correctly.. that's my original code:

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

var family = new Array();

var family[0] = new Person("alice", 40);
var family[1] = new Person("bob", 42);
var family[2] = new Person("michelle", 8);
var family[3] = new Person("timmy", 6);

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

i still get the error..


#4

Try this: You have added var before the family[0], family[1],...so on. Since the values are added in the array, so there is no need of var before that.

// Our Person constructor
function Person (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
for(var i = 0 ; i < family.length ; i++ ){
console.log(family[i].name);
}


#5

you are the man! thank you!!!