• 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

  • 相关阅读:
    ftoa浮法成字符串
    iOS UIWebView键盘操控
    开始Unity3D参观考察
    中国目前拥有的物种和人造卫星的作用
    robin 今日南
    编写自己的单点登录(SSO)服务
    poj 2385 Apple Catching dp
    OSI七层模型具体解释
    Android学习路径(四)文件项目学习的名单,android显示单元经常使用的
    单元测试概述
  • 原文地址:https://www.cnblogs.com/ooo0/p/6700960.html
Copyright © 2020-2023  润新知