📅 April 26, 2017
What if we want to grab an integer, say, from 1 to 25 inclusive?
We can do this easily by modifying the random result to our liking.
Suppose we have a subdirectory (named weather) of small icons named 001.png to 025.png sequentially. Our script will pick one at random by generating a random number from 1 to 25 using Math.random().
Write a test HTML5 file and place the script within the body.
The trick is the line
var num = Math.floor(Math.random() * 25) + 1;
There are three points combined into one.
- Math.random() returns 0 to 0.99999~. We want an integer result such as 2, 3, and 20. To do this, we multiply by 25, which is the upper limit. This gives us something like 10.456344, 2.3445566, or 24.595834.
- To remove the floating-point part and keep only the integer, we must pass the result to the Math.floor() function to round down. This now gives us 10, 2, or 24 (from the example above).
- We have a problem. The range is 0 to 24. We need 1 to 25, so we add 1 to the result. This gives us the range we need: 1 to 25.
Now that we are generating a valid random number within the range 1 to 25, we need to modify it into a valid filename.
All icons are stored in a directory called weather, so iconFilename will initialize to weather/ (yes, with the forward slash).
The if statement checks the value. If 1 through 9, then two 00’s are prefixed along with the .png filename extension. If not, which assumes 10+, then only one 0 is prefixed. This is because all icon filenames contain three digits. The code as written does not pad to three places.
As an example, here are a few results:
Math.random() Result ---------------------------- 1 weather/001.png 10 weather/010.png 25 weather/025.png
Open the html file in a browser. We should see a random weather icon appear.
The text weather/003.png is produced by document.write(iconFilename) for debugging purposes.
document.getElementById("weathericon").src = iconFilename;
to dynamically change the icon shown by the img element, which was given an id of weathericon.
Refresh the browser to see another icon.
I Do Not See Any Icons