javascript 实现随机数

来源:互联网 发布:腹黑兔子无耻外交 知乎 编辑:程序博客网 时间:2024/04/27 14:57
<script type="text/javascript"><!--google_ad_client = "pub-4490194096475053";/* 内容页,300x250,第一屏 */google_ad_slot = "3685991503";google_ad_width = 300;google_ad_height = 250;// --></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>
Math对象中的方法
Math.random() 该方法返回一个0到1之间的随机数,不包括0和1。
要实现获得一个maxNumber到minNumber范围内的随机整数,实现方法如下:
choNumber=maxNumber-minNumber+1;
number=Math.floor(Math.random()*choNumber+minNumber)

例:
选择一个1到10之间的随机数:
number=Math.floor(Math.random()*10+1);
可能出现的值有10个,最小的值为1。
选择一个2到10之间的随机数:
number=Math.floor(Math.random()*9+2);
可能出现的值有9个,最小的值为2。
解释:Math.floor()用来获取一个整数,将小数转换成整数。

通过函数实现从一个数组中随机选择一个值:
实现selectFrom()函数获得一个iFirstValue到iLastValue之间的随机整数
function selectFrom(iFirstValue,iLastValue)
{
var iChoices=iLastValue-iFirstValue+1;
return Math.floor(Math.random()*iChoices+iFirstValue);
}

例:


var aColors=["red","green","yellow","black","blue","purple","brown"];
var sColors=aColors[selectFrom(0,aColors.length-1)]

 
原创粉丝点击