27. Loop the Loop | Introduction to objects I


#1

Hi, I have the following code:

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

It claims that it does not understand the less than sign (<). The error states,
"SyntaxError: Unexpected token <"
Does anyone know what is wrong?


#2

The for-statement creates a loop that consists of

  • three optional expressions,
  • enclosed in parentheses and separated by semicolons,
  • followed by a statement or a set of statements executed in the loop.

Syntax

for ([initialization]; [condition]; [final-expression])
   statement

In your for-loop definition
you are using a comma-, as a separator,
between [initialization] and [condition]
for(var i = 0 , i < family.length; i++) {
this should be a semi-colon-;.


#3

Thank you so much! It worked!


#4

Guys I have a question:
Is my code bad ? It works but the program writes an error.

// Our Person constructor
function Person (name, age) {
    this.name = name;
    this.age = age;
};
// Now we can make an array of people
var family = [];
while (family.length != 4) {
    family.push(new Person (prompt("Name"), prompt("Age")));
};
// loop through our new array
for (var x in family) {
    console.log(family[x].name);
};

#5

@edelweiss719,

1

It would be nice to know, WHAT does the error SAY....

2 ( For-in on Array =not Recommended= )

The FOR-IN loop is thought to be for inspecting objects
but you must be aware that it also traverses the prototype-chain.
To be sure that the property is coming from the inspected Object
and NOT from some prototype in its prototype-chain
you would have to write

for (var x in family) {
    if ( family.hasOwnProperty(x) ) {
       console.log(family[x].name);
    }
    else {
       console.log( "The "+ x + " property is from a prototype" );
    }
}

For a == discussion / opinion == do a google search
javascript using a for in on an Array site:stackoverflow.com
for instance:
= http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea

3

The fasted way would be using a FOR-loop
like

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

4

You must be aware that windows.prompt() method will allways return a string Value.
So, if you want the age to be a number Value you would have to use

parseInt(prompt("Age"),10)

thus

while (family.length != 1) {
    family.push(new Person (prompt("Name"), 
                   parseInt(prompt("Age"),10) ) );
}