DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript產生隨機數方法匯總
javascript產生隨機數方法匯總
編輯:關於JavaScript     
<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;
}

1.Math.random(); 結果為0-1間的一個隨機數(包括0,不包括1)
2.Math.floor(num); 參數num為一個數值,函數結果為num的整數部分。
3.Math.round(num); 參數num為一個數值,函數結果為num四捨五入後的整數。

Math:數學對象,提供對數據的數學計算。
Math.random(); 返回0和1間(包括0,不包括1)的一個隨機數。

Math.ceil(n); 返回大於等於n的最小整數。
用Math.ceil(Math.random()*10);時,主要獲取1到10的隨機整數,取0的幾率極小。

Math.round(n); 返回n四捨五入後整數的值。
用Math.round(Math.random());可均衡獲取0到1的隨機整數。
用Math.round(Math.random()*10);時,可基本均衡獲取0到10的隨機整數,其中獲取最小值0和最大值10的幾率少一半。

Math.floor(n); 返回小於等於n的最大整數。
用Math.floor(Math.random()*10);時,可均衡獲取0到9的隨機整數。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved