zoukankan      html  css  js  c++  java
  • 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());
  • 相关阅读:
    《JavaScript高级程序设计》学习笔记12篇
    JS学习笔记12_优化
    JS学习笔记11_高级技巧
    JS学习笔记10_Ajax
    JS学习笔记9_JSON
    JS学习笔记8_错误处理
    为什么要在列表组件里写 Key ?
    var、let 和 const 的区别以及暂时性死区
    小程序性能优化要点
    Node require() 加载规则
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/13790454.html
Copyright © 2011-2022 走看看