How do I make a page generate and display four random numbers in the 0 to 9 range?
<html>
<body>
<div style="text-align:center"><h2>Lucky Mo's Gift to You</h2>
<p>Numbers rule our lives. If you would like the benefit of Lucky Mo's amazing powers
of prognostication, click on the button below to receive your guaranteed lucky number
of the day!</p>
<input type="button" value="Click Here For Today's Pick-4 Winner"
onclick="luckynum = Math.floor((9-0)*Math.random());
ale开发者_JAVA技巧rt('your Pick-4 winners are ' + luckynum);" />
</div>
</body>
</html>
You could build a string for your case:
<script type="text/javascript">
function randomNumbers()
{
var numbers = "your Pick-4 winners are ";
for(var i = 0; i < 4; i++)
{
numbers += Math.floor((9-0)*Math.random()) + " ";
}
alert(numbers);
}
</script>
<input type="button" value="Click Here For Today's Pick-4 Winner" onclick="randomNumbers()" />
Or if you want to guarantee that the four numbers are different:
<script type="text/javascript">
function randomNumbers()
{
var numbers = [-1, -1, -1, -1];
for(var i = 0; i < 4; i++)
{
var num = -1;
while(contains(numbers, num))
{
num = Math.floor((9-0)*Math.random());
}
numbers[i] = num;
}
alert("Your Pick-4 winners are: " + numbers);
}
function contains(array, num)
{
for(var i = 0; i < array.length; i++)
{
if(array[i] == num)
return true;
}
return false;
}
</script>
精彩评论