Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
From the author of Generating Random Numbers

Generating Random Numbers

Now that we can trigger our function successfully, let's write the code that goes inside it. We need to generate a random number from 1 to 5 to use in selecting our pictures. That bit of code looks like this:

var randomNum = Math.round(Math.random()*5)+1;

This is a very compact expression, so let's break it down.

It helps to remember that the part of the expression in the innermost parentheses is evaluated first. The Math.random() method returns a random number between 0 and 1 to lots of decimal places—something like 0.34344356. We multiply this result by five—the number of images we want to rotate—to obtain a number somewhere between 0 and 4. By wrapping the Math.floor() method around this expression, the number generated is rounded down to the nearest whole number. The value is still between 0 and 4, so we finally add 1 to get a value between 1 and 5, which is what we want. The variable randomNum is set to the result of this calculation. Now we're programming!

One immediate small improvement is to change 5 in the expression to a variable, making it easier for someone using the script to change the number of pictures that need to be rotated (without having to touch this rather complex expression):

function pickAPic () {
        var picCount = 5; // set the number of pics to rotate here
        var randomNum = Math.floor(Math.random()*picCount)+1;
        alert (randomNum);
}

Let's use an alert to display the randomNum variable and load the page a few times so we can check that we're generating the right range of values (see Figure 3):

function pickAPic () {
        var randomNum = Math.floor(Math.random()*5)+1;
        alert (randomNum);
}

Figure 3 Each time we load the page, a new random number between 1 and 5 is generated.

  • + Share This
  • 🔖 Save To Your Account