Math.random
In this chapter you will learn:
- How to use Math random method
- How to get a random number in a range
- How to get a random value from an array
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><!--from j a va 2 s. c o m-->
<html>
<head>
<script type="text/javascript">
var num = Math.floor(Math.random() * 10 + 1);
document.writeln(num);
</script>
</head>
<body>
</body>
</html>
Random in a range
To select a number between 2 and 10:
<!DOCTYPE html><!--from ja v a 2 s. c o m-->
<html>
<head>
<script type="text/javascript">
var num = Math.floor(Math.random() * 9 + 2);
document.writeln(num);
</script>
</head>
<body>
</body>
</html>
Random value from an array
To select a random item from an array:
<!DOCTYPE html><!-- j a va2 s. c o m-->
<html>
<head>
<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>
Next chapter...
What you will learn in the next chapter: