»
 

Go Back   ResellerRatings Store Ratings > ResellerRatings Forums > Tech Support

Reply
 
LinkBack Thread Tools Display Modes
Old 04-26-2004, 11:33 AM   #1 (permalink)
Registered User
 
Join Date: Oct 2001
Posts: 3,539
ClubMed is on a distinguished road
Javascript Help Needed

Here is javascript which should output a random string from the ones defined:

<!--
var r_text = new Array ();
r_text[0] = "Violence is the first refuge of the incompetent. ~Issac Asimov";
r_text[1] = "1";
r_text[2] = "2";
r_text[3] = "3";
r_text[4] = "4";
r_text[5] = "5";
var i = Math.round(6*Math.random());

document.write(r_text[i]);
//-->

For some reason, the output is: "undefined" sometimes.

Can anyone tell me why this is happening?

ClubMed is offline   Reply With Quote
Old 04-26-2004, 12:46 PM   #2 (permalink)
Guest
Guest
 
Posts: n/a
Try var i = math.floor(math.random() * 6);

What's happening is you're getting a value like 5.95 and math.round is rounding it to 6 which isn't a valid value for your array. math.floor rounds down always so you'll always get 0 - 5 with the above line.




I think I've edited this seventeen times now...
  Reply With Quote
Old 04-27-2004, 03:57 AM   #3 (permalink)
Registered User
 
Join Date: Oct 2001
Posts: 3,539
ClubMed is on a distinguished road
okay thanks very much.

if i add more lines will it still work with your improvement?
ClubMed is offline   Reply With Quote
Old 04-27-2004, 04:30 AM   #4 (permalink)
Guest
Guest
 
Posts: n/a
As long as you also increase the the multiplier to your array limit + 1, it should always work.

What I would do is this:

var i = Math.Floor(Math.Random * r_text.length)

That way no matter how many things you choose to put into the array, the multiplier will always be correct (the .length of an array is always one larger than the largest value of the array so no + 1 is needed). I thought about that the first time, and then forgot to put it in the post.
  Reply With Quote
Old 04-27-2004, 07:46 AM   #5 (permalink)
Registered User
 
Join Date: Oct 2001
Posts: 3,539
ClubMed is on a distinguished road
okay thank you.
ClubMed is offline   Reply With Quote
Reply




Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Most Active Discussions

Recent Discussions

All times are GMT -6. The time now is 07:07 PM.