JS生成隨機(jī)數(shù)詳解
<script> function GetRandomNum(Min,Max){ var Range = Max - Min; var Rand = Math.random(); return(Min + Math.round(Rand * Range)); } var num = GetRandomNum(1,10); alert(num); </script>
生成隨機(jī)字符串
function generateMixed(n) { 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']; var res = ""; for(var i = 0; i < n ; i ++) { var id = Math.ceil(Math.random()*35); res += chars[id]; } return res; }
Math.random();
結(jié)果為0-1間的一個(gè)隨機(jī)數(shù)(包括0,不包括1)
Math.floor(num);
參數(shù)num為一個(gè)數(shù)值,函數(shù)結(jié)果為num的整數(shù)部分。
Math.round(num);
參數(shù)num為一個(gè)數(shù)值,函數(shù)結(jié)果為num四舍五入后的整數(shù)。
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);
主要獲取1到10的隨機(jī)整數(shù),取0的幾率極小。
Math.round(n);
返回n四舍五入后整數(shù)的值。
用Math.round(Math.random());
可均衡獲取0到1的隨機(jī)整數(shù)。
Math.round(Math.random()*10);
可基本均衡獲取0到10的隨機(jī)整數(shù),其中獲取最小值0和最大值10的幾率少一半。
Math.floor(n);
返回小于等于n的最大整數(shù)。
Math.floor(Math.random()*10);
可均衡獲取0到9的隨機(jī)整數(shù)。
推薦教程:《JS基礎(chǔ)教程》