Bucaro TecHelpHTTPS Encryption not required because no account numbers orpersonal information is ever requested or accepted by this site Custom Search

# Generating Random Numbers

The Math.random method returns a floating-point value between 0 and 1. To generate a random integer between zero and n, use the formula below:

```var num = Math.floor(Math.random() * n);
```

To generate a random integer between m and n, use the formula below:

```var num = Math.floor(Math.random() * (n - 1)) + m;
```

For example, if you wanted to design a card game you would need random integers between 1 and 52. These random numbers could be generated with the line shown below.

```var card = Math.floor(Math.random() * 51) + 1;
```

The example below places the names of the cards in an array and then generates a random integer between 1 and 52, which it uses as an index into the array to display the name of a card.

```var arCard = new Array(
"A club","2 club","3 club","4 club","5 club","6 club","7 club","8 club","9 club","10 club","J club","Q club","K club",
"A diam","2 diam","3 diam","4 diam","5 diam","6 diam","7 diam","8 diam","9 diam","10 diam","J diam","Q diam","K diam",
"A heart","2 heart","3 heart","4 heart","5 heart","6 heart","7 heart","8 heart","9 heart","10 heart","J heart","Q heart","K heart",
var card = Math.floor(Math.random() * 52) + 1;
document.write(arCard[card]);
```

You might use a for loop, as shown below, to "draw" a random five card poker hand. Each time the webpage is loaded, a random poker hand will be displayed.

```var card;
for(var i = 1; i < 6; i++)
{
card = Math.floor(Math.random() * 52) + 1;
document.write(arCard[card] + " - ");
}
```

The example below places the file names for six die images into an array. Each time the webpage is loaded, a random pair of die images will be displayed.

```var arDie = new Array("1.gif","2.gif","3.gif","4.gif",
"5.gif","6.gif");
var roll;

for(var i = 1; i < 3; i++)
{
roll = Math.floor(Math.random() * 5) + 1;
document.write("<img src='" + arDie[roll] + "'>");
}
```

Random numbers have many uses, from the creation of passwords, generation of abstract art, generation of artificial worlds, to games such as dice and cards. The Java Script Math object's random method returns a floating-point value between 0 and 1. To generate a random integer between zero and n, use the formula provided here.

 .menubtn { margin-top:10px; margin-left:50px; width:220px; opacity:1; border-style:solid; border-color:#009000; background-color:#66ff66; transition-property: opacity; transition-duration: 1s; transition-timing-function: ease-out; } .menubtn:hover { opacity:1; background-color:#e5ff23; } Menu - More Java Script Quick Reference RSS Feed  Follow @Stephen Bucaro
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2019 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268