JavaScript Tutorial/Math/random

Материал из Web эксперт
Перейти к: навигация, поиск

Generate a random integer between 2 and 10

<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
function selectFrom(startValue, endValue) {
    var iChoices = endValue - startValue + 1;
    return Math.floor(Math.random() * iChoices + startValue);
}

var iNum = selectFrom(2, 10);
alert(iNum);
</script>
</body>
</html>


Generate random numbes in a range

<html>
<head>
<title>die Roller</title>
<script>
var rollRaw = 0;
var rollBigger = 0;
var rollInt = 0;
var rollFinal = 0;
var result = "";
rollRaw = Math.random();
rollBigger = rollRaw * 6;
rollInt = Math.floor(rollBigger);
rollFinal = rollInt + 1;
result = "rollRaw: " + rollRaw + "\n";
result += "rollBigger: " + rollBigger + "\n";
result += "rollInt: " + rollInt + "\n";
result += "rollFinal: " + rollFinal + "\n";
alert(result);
</script>
</head>
<body>
</body>
</html>


Generate random URL

<HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--
var rand_url= new Array()
rand_url[0]="http://www.wbex.ru";
rand_url[1]="http://www.wbex.ru";
rand_url[2]="http://www.wbex.ru";
rand_url[3]="http://www.wbex.ru";
rand_url[4]="http://www.wbex.ru";
var rand_num= Math.floor(Math.random()*5);
//-->
</SCRIPT>
</HEAD>
<BODY>
<H2>List of Cars:</H2>
<SCRIPT language="JavaScript">
<!--
 document.write("<A HREF=""+rand_url[rand_num]+"">"+rand_url[rand_num]+"</A>");
//-->
</SCRIPT>
</BODY>
</HTML>


Math.random()

Syntax



math.random(num)


Math.round a random number

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
rndNum = Math.random();
rndNum = rndNum * 100;
alert(Math.round(rndNum));
//  -->
</script>
</head>
<body>
</body>
</html>


Use Math.random to generate random number

<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
    alert(Math.random());
//  -->
</script>
</head>
<body>
</body>
</html>