HTML Goodies: Script Tip: Week 16
Mr. Tip, I presume?
Okay, hey! New script this week! This script is great in that it produces a random number between 1 and any number. You can set the upper limit within the script. The output of the script looks like this:
And here's what it all looks like:
return Math.round(upper_limit * Math.random());
var upper_limit = 50;
document.write('Here is a random number between 0 and '
+ upper_limit + ':<P><center>');
document.write(RandomNumber(upper_limit) + '</center>');
Wait (you yell)! That's not one script, that's two!
But they work with each other. The first script actually creates the random number. The second is mainly there to set the upper limit and display the results. It's a pretty clever script. Look at the line that creates the random number to start it off.
Let's break it down so it's readable. "Math" is an object, but it's a strange object. It itself isn't really anything except a socket with which you can connect methods. It's just that when you use the Math object, you are stating to the browser that this script deals directly with numbers and mathematics.
"round" (note lack of capitalization) is a method that rounds off the number that "Math" will soon represent.
So, let's read the line. Return to the script a rounded-off version (Math.round) of the upper_limit (not yet set), times (*) a random number between 0 and 1 (Math.random()). If the upper limit is set to 50, you would get one of 50 different answers, and since the round method rounds up, you'll never get a zero.
Make a note of where all the parentheses are. The upper limit number and the random number between 0 and 1 are figured first. Then the number is rounded. Remember that from high school algebra? What's inside the ( ) gets figured first.
That's the mathematics of it all. But where does the upper limit come from? Why, it's the function itself! See you next week.
Next Week: The Upper Limit
HTML Goodies 30-Step Primer Series
and take the knowledge home with you in
on your Web pages here!