How to use Math random method

Description

The Math.random() method returns a random number between the 0 and the 1, not including either 0 or 1.

Math.random() output within a certain integer range by using the following formula:

number = Math.floor(Math.random() * total_number_of_choices + first_possible_value)

Example

To select a number between 1 and 10:


var num = Math.floor(Math.random() * 10 + 1); 
console.log(num);

The code above generates the following result.

Random in a range

To select a number between 2 and 10:


var num = Math.floor(Math.random() * 9 + 2); 
console.log(num);

The code above generates the following result.

Random value from an array

To select a random item from an array:


function selectFrom(lowerValue, upperValue) {
   var choices = upperValue - lowerValue + 1;
   return Math.floor(Math.random() * choices + lowerValue);
}    /* w  w w  . j  a va2  s  . c o m*/
    
var colors = ["A", "B", "C", "D", "E", "F", "G"]; 
var color = colors[selectFrom(0, colors.length-1)]; 
console.log(color);

The code above generates the following result.

Example 2


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
  var rand_url = new Array()
  rand_url[0] = "http://www.java2s.com";
  rand_url[1] = "http://www.java2s.com";
  rand_url[2] = "http://www.java2s.com";
  rand_url[3] = "http://www.java2s.com";
  rand_url[4] = "http://www.java2s.com";
<!--from ww w .ja va  2  s .  c  o  m-->
  var rand_num = Math.floor(Math.random() * 5);

  document.write("<A HREF='"+rand_url[rand_num]+"'>" + rand_url[rand_num]
      + "</A>");
</script>
</head>
<body>
</body>
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window