JS封装 随机数

// 手写可控rendom()函数
let seed = new Date();
function random(){
    let x = Math.sin(seed++) * 10000;
    return x - Math.floor(x);
}
console.log(random());
// 洗牌算法
let arr = [1, 2, 3, 4, 5, 6];
function shuffle(arr){
    for(let i = arr.length - 1; i >= 0; i--){
        let randomIndex = Math.floor(Math.random() * (i + 1));
        let itemAtIndex = arr[randomIndex];
        arr[randomIndex] = arr[i];
        arr[i] = itemAtIndex;
    }
    return arr;
}
console.log(shuffle(arr));
// 洗牌算法 - 数组原型方法
Array.prototype.shufflePro = function () {
    let input = this;
    for (let i = input.length - 1; i >= 0; i--) {
        // let randomIndex = Math.floor(Math.random() * (i + 1));
        let randomIndex = Math.floor(Math.random() * input.length);
        let itemAtIndex = input[randomIndex];
        input[randomIndex] = input[i];
        input[i] = itemAtIndex;
    }
    return input;
}
let tempArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(tempArray.shufflePro());
// 加密随机数1
function luckyNum(n = 1){
    let array = new Uint32Array(n);
    let luckyArr = [];
    window.crypto.getRandomValues(array);
    for (var i = 0; i < array.length; i++) {
        luckyArr.push(array[i]);
    }
    console.log(n);
    return luckyArr;
}
console.log(luckyNum());
// 加密随机数2
function luckyNum(n = 1, m = 2){   
    console.log(n);
    let array = new Uint32Array(n);
    let luckyArr = [];
    window.crypto.getRandomValues(array);
    for (var i = 0; i < array.length; i++) {
        luckyArr.push(array[i].toString().slice(0, m)*1);
    }
    return luckyArr;
}
console.log(luckyNum());
原文地址:https://www.cnblogs.com/SharkJiao/p/13790454.html