Can anyone explain this error


#1

i am in loop the loop in introducton to objects
here is the question:Write a person constructor called Person that has two properties (name and age).
Create an empty array called family.
There will be four objects in the array. Using your Person constructor, create the four objects and put them in the array. The order of the objects are:

"alice" who is 40
"bob" who is 42
"michelle" who is 8
"timmy" who is 6
Create a for-loop that loops through the family array and prints out the name property for each family member in order of creation.

The code that i wrote:
function Person(name,age)// Our Person constructor
{
this.name=name;
this.age=age;
}
var family= new Array();

for(var i=0;i<4;i++)
{
var name=prompt("enter the name");
var age=prompt("enter age of "+name);
family[i]=new Person(name,age);

}// Now we can make an array of people

for (var prop in family )
{
console.log(family[prop]);
}

output:
{ name: 'alice', age: '40' }
{ name: 'bob', age: '42' }
{ name: 'michelle', age: '8' }
{ name: 'timmy', age: '6' }


We're running a test below to make sure your code works.
{ name: 'alice', age: '40' }{ name: 'bob', age: '42' }{ name: 'michelle', age: '8' }{ name: 'timmy', age: '6' }

error:Oops, try again. It looks like the Person at index 0 isn't 40 years old


#2

Your .. "numbers" are strings, '40' isn't equal to 40
Hard-code the persons instead of entering them manually.
Or convert the numerical stuff from string to number (I don't know how to do that, but perhaps you do, otherwise google.. or hard-code it as intended)


#3

could u be a little more specific on what i should try?thank u:smiley:


#4

hello @javawhiz30307

you can use parseInt(string, base);

exemple:

var age=parseInt(prompt("enter age of "+name), 10);


#5

thanks a lot that worked


#6

@aureolebigben what about the Number constructor? Other than being able to specify a radix, does parseInt do anything that the Number constructor doesn't?


#7

I think number constructor is more complete but i generally use parseInt() just because it's a personal preference (no reason for this).
Number object has the method parseInt() but it's experimental.