<Lesson 24> [Contents] <Lesson 26>
25.1: Generating random numbers of an array in JavaScript
We have learned about a random generation of numbers in Javascript Lesson 14. However, in this lesson, you will learn how to generate random numbers using an array. Since every element in an array is identified by a subscript, hence by randomizing the subscripts we will be able to generate random elements of the array.
The randomizing process can be carried using the random method of the Math object. Math.random( ) generates numbers between 0 and 1. Therefore, to obtain random numbers between 0 and 6, we need to multiply Math.random( ) with 6, i.e Math.random( )*6. However, to obtain random integers between 0 and 6, we need to use the floor method of the Math object. The floor(x) method returns the greatest integer less than or equal to x. For example, Math.floor(5.4)=5
Equip with the above knowledge in mind, we shall proceed to write a subscript to simulate the throwing of a die that contains six faces and numbered 1, 2, 3,4,5,6.
The following is the script:
<html> <head> <title>Sorting an Array of Images</title> <script type = "text/javascript"> <!-- var Numbers = [ 1,2,3,4,5,6];document.write (Numbers[ Math.floor( Math.random( ) * 6 ) ] ); // --> </script></head><body></body> </html>
In this example, Math.floor( Math.random( ) * 6 ) produces random integers between 0 and 5, i.e 0,1,2,3,4,5. Thus,
Numbers[ Math.floor( Math.random( ) * 6 ) ] produces random elements of the array with subscript 0,1,2,3,4 or 5, in this way we can generating random numbers 1 to 6, resembling the throwing of a die.
Click Example 25.1 to view the actual output.
25.2: Generating random strings of an array
If an array is made up of strings or words, we can also generate random strings or words using the same reasoning. Each string is identified by a subscript, by randomizing the subscripts we can then generate random strings based on their subscripts.
The code is shown below:
<html > <head> <title>Sorting an Array of Images</title> <script type = "text/javascript">var fruits = [ "cherry", "grape", "orange"];document.write (fruits[Math.floor( Math.random() * 3 )]); </script> </head><body></body> </html>
Click Example 25.2 to view the actual output
25.3 Generating random images using Array
Now we shall go a step further, generating random images using the same reasoning as above. Each image is identified by is subscript, therefore by randomizing the subscripts we can then create random images. To display the images, we just need to use the <img> tag.
The complete script is shown below:
<html> <head> <title>Sorting an Array of Images</title> <script type = "text/javascript">var images = [ "cherry", "grape", "orange"];document.write ( "<img src = \"" +images[ Math.floor( Math.random() * 3 ) ] +".gif\" width = \"75\" height = \"75\" />" ); </script> </head><body></body> </html>
Click Example 25.3 to view test the actual output.