random() Method
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)
To select a number between 1 and 10:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var num = Math.floor(Math.random() * 10 + 1);
document.writeln(num);
</script>
</head>
<body>
</body>
</html>
To select a number between 2 and 10:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
var num = Math.floor(Math.random() * 9 + 2);
document.writeln(num);
</script>
</head>
<body>
</body>
</html>
To select a random item from an array:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript">
function selectFrom(lowerValue, upperValue) {
var choices = upperValue - lowerValue + 1;
return Math.floor(Math.random() * choices + lowerValue);
}
var colors = ["A", "B", "C", "D", "E", "F", "G"];
var color = colors[selectFrom(0, colors.length-1)];
document.writeln(color);
</script>
</head>
<body>
</body>
</html>