先為大家介紹一些關(guān)于隨機(jī)數(shù)的相關(guān)函數(shù):
var Rand = Math.random();
Math:數(shù)學(xué)對(duì)象,提供對(duì)數(shù)據(jù)的數(shù)學(xué)計(jì)算。
Math.random(); 返回0和1間(包括0,不包括1)的一個(gè)隨機(jī)數(shù)。
Math.ceil(n); 返回大于等于n的最小整數(shù)。
用Math.ceil(Math.random()*10);時(shí),主要獲取1到10的隨機(jī)整數(shù),取0的幾率極小。
Math.round(n); 返回n四舍五入后整數(shù)的值。
用Math.round(Math.random());可均衡獲取0到1的隨機(jī)整數(shù)。
用Math.round(Math.random()*10);時(shí),可基本均衡獲取0到10的隨機(jī)整數(shù),其中獲取最小值0和最大值10的幾率少一半。
Math.floor(n); 返回小于等于n的最大整數(shù)。
用Math.floor(Math.random()*10);時(shí),可均衡獲取0到9的隨機(jī)整數(shù)。
隨機(jī)抽獎(jiǎng),還可擴(kuò)展,比如設(shè)置抽獎(jiǎng)的概率,和數(shù)據(jù)庫一起使用。
//中獎(jiǎng)概率需求,100%中獎(jiǎng),有3項(xiàng)獎(jiǎng)品,但是抽到書本的概率為20%function draw() { var d_s = GetRandom(100); if (d_s >= 1 && d_s <= 40) { alert('恭喜您抽到XXX!'); } else if (d_s >= 41 && d_s <= 80) { alert('恭喜您抽到XXX!'); } else { alert('恭喜您抽到書本!'); }}對(duì)應(yīng)的js生成隨機(jī)數(shù)的函數(shù)代碼:
<script> 2function GetRandomNum(Min,Max){ var Range = Max - Min; var Rand = Math.random(); return(Min + Math.round(Rand * Range)); } 8var num = GetRandomNum(1,10); 9alert(num); </script>var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];function generateMixed(n) { var res = ""; for(var i = 0; i < n ; i ++) { var id = Math.ceil(Math.random()*35); res += chars[id]; } return res;}以上就是本文的詳細(xì)內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注