View Full Version : 'Undefined' Error

09-22-2005, 12:30 AM
Ok- I have three arrays, and then I have a function generate a random number for a variable in the array. Then it puts it together in a word. It's for a random name generator, by the way. The problem is that sometimes everything works fine and I get a nice word made from 3 random parts of the array, but sometimes one of the parts comes up as undefined. Can anybody help? Here's some of the coding, shortened:

// 1st List Values
list1=new Array(3);


// 2nd List Values
list2=new Array(3);


// 3rd List Values
list3=new Array(3);


function gen_name()
var v1;
var v2;
var v3;
var v4;

var x1;
var y1;
var z1;

x1=Math.floor(Math.random()* 3) + 1;
y1=Math.floor(Math.random()* 3) + 1;
z1=Math.floor(Math.random()* 3) + 1;

fantasyname.innerText=list1[x1] + list2[y1] + list3[z1];

(this little bit from the var v1 to the fantasyname.innerText part is repeated several times, and it's the same except for 'fantasyname2, 3, 4, 5' etc. Then later on it outputs that number of names.)

Sorry if I'm explaining really badly or I am just being a total noob here... I'm new to Javascript, obviously. At this point I have no idea what I could be doing wrong so help is extremely appreciated. Thanks. :)

09-22-2005, 02:31 AM
I think your random number is too high.

I am assuming you want a number between 1 and 3.
So you random number generator should be (Math.random()*2)+1.

You random numbers right now are between 1 and 4, not 1 and 3. So when you get undefined, i am guessing that it was using the number 4.

The general formulate for random numbers is:

(Math.random() *(max-min)) + min.

Hope that helps.

09-22-2005, 03:03 AM
With this part...

// 1st List Values
list1=new Array(3);


Wouldn't you have to start from 0? Like this.

// 1st List Values
list1=new Array(3);


09-22-2005, 03:05 AM
You don't have to. Element 0 in the array would be undefined, but if you never use it, it won't matter at all.

That is why he needs a random number from 1 to 3, not 0 to 2.

09-23-2005, 12:01 AM
And the way he coded the random number generator was occasionally referencing the non-existant zeroth entry hence returning undefined.

09-23-2005, 12:03 AM
Not true. It was referencing the non-existant 4th element. The +1 at the end, makes the number never be less than 1.

09-23-2005, 12:05 AM
Umm... I'm a she, lol, but thanks for your help everyone. I fixed the problem, now they work fine. Thanks again!

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum