js 獲取隨機數 Math.random()


js 獲取隨機數 Math.random()

 

// 結果為0-1間的一個隨機數(包括0,不包括1) 
var randomNum1 = Math.random();
//console.log(randomNum1);

// 函數結果為入參的整數部分。 
var randomNum2 = Math.floor(randomNum1);
//console.log(randomNum2);

// 函數結果為入參四舍五入后的整數。
var randomNum3 = Math.round(randomNum1);
//console.log(randomNum3);

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

// Math.round(n); 返回n四舍五入后整數的值。
var randomNum5 = Math.round(Math.random()); // 可均衡獲取0到1的隨機整數。
//console.log(randomNum5);
var randomNum6 = Math.round(Math.random() * 10); // 可基本均衡獲取0到10的隨機整數,其中獲取最小值0和最大值10的幾率少一半。
//console.log(randomNum6);

// Math.floor(n); 返回小於等於n的最大整數。
var randomNum7 = Math.floor(Math.random() * 10); // 可均衡獲取0到9的隨機整數。
//console.log(randomNum7);

// 獲取最小值到最大值之前的整數隨機數
function GetRandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return(Min + Math.round(Rand * Range));
}
var num = GetRandomNum(1, 10);
//console.log(num);

//獲取n位隨機數,隨機來源chars
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;
}
var num1 = generateMixed(6);
//console.log(num1);

 

 

 

http://www.cnblogs.com/banbu/archive/2012/07/25/2607880.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM