js常用內容彙總
js生成隨機數
Math.ceil(); //向上取整。
Math.floor(); //向下取整。
Math.round(); //四捨五入。
Math.random(); //0.0 ~ 1.0 之間的一個偽隨機數。【包含0不包含1】 //比如0.8647578968666494
Math.ceil(Math.random()*10); // 獲取從1到10的隨機整數 ,取0的概率極小。
Math.round(Math.random()); //可均衡獲取0到1的隨機整數
Math.floor(Math.random()*10); //可均衡獲取0到9的隨機整數。
Math.round(Math.random()*10); //基本均衡獲取0到10的隨機整數,其中獲取最小值0和最大值10的機率少一半。
因為結果在0~0.4 為0,0.5到1.4為1...8.5到9.4為9,9.5到9.9為10。所以頭尾的分佈區間只有其他數字的一半。
//生成從minNum到maxNum的隨機數
function randomNum(minNum,maxNum){
switch(arguments.length){
case 1:
return parseInt(Math.random()*minNum+1,10);
break;
case 2:
return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10);
break;
default:
return 0;
break;
}
}