js 随机函数

JavaScript011

js 随机函数,第1张

在写js中,我们经常遇见 js 随机函数,总结一下最近写验证码的时候  用到过的js 随机函数

Math.random()结果为0-1间的随机数(包括0,不包括1)

Math.floor( n )参数为Number 类型 ,函数结果 为num 的整数部分

Math.round( n ) ; 参数为Number 类型。函数结果 为num 四舍五入部分

Math.ceil( n )参数为Number类型。 函数结果为大于等于n的整数

Math.ceil(Math.random()*10) : 主要获取1到10的随机整数,取0的几率极小。

Math.round(Math.random()) : 可均衡获取0到1的随机整数

Math.round(Math.random()*10)  可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半

Math.floor(Math.random()*10) 可均衡获取0到9的随机整数

例子:

    1. 实现一个 随机 汉字

         randomChi(){   // 随机生成汉字

                return `\\u${Math.round(Math.random() * 20901 + 19968 ).toString(16)}`

           }

    2. 实现一个n - m 的整数 ( 参照于 http://www.jb51.net/article/56019.htm )

        生成 n-m , 包含n 但不包含 m的整数

            第一步算出 m -n的值,假设等于 w 

            第二步 Math.random( )  * w

            第三步 Math.random() * w +n

            第四步 parseInt( Math.random() * w +n, 10)

         生成一个 n-m ,包含 m 但不包含 n的整数

            第一步算出 m-n的值,假设等于w

            第二步Math.random()*w

            第三步Math.random()*w+n

            第四步Math.floor(Math.random()*w+n) + 1

         生成一个不包含 n -m 但都不包含 n  和 m

             第一步算出 m-n-2的值,假设等于w

              第二步Math.random()*w

              第三步Math.random()*w+n +1

               第四步Math.round(Math.random()*w+n+1) 或者 Math.ceil(Math.random()*w+n+1)

            生成n-m,包含n和m的随机数:

                第一步算出 m-n的值,假设等于w

                第二步Math.random()*w

                第三步Math.random()*w+n

                第四步Math.round(Math.random()*w+n) 或者 Math.ceil(Math.random()*w+n)

             实例: 生成800-1500的随机整数,包含800但不包含1500

                1500-800 = 700

                Math.random()*700

                var num = Math.random()*700 + 800

                num = parseInt(num, 10)

更多实例 请查看  https://github.com/Mrangmaomao

用JS的随机数生成函数random()配合其他数学函数可以限制随机数的取值。

JS的随机数函数及相关函数:

Math.random()结果为0-1间的一个随机数(包括0,不包括1) 。

Math.floor(num)参数num为一个数值,函数结果为num的整数部分。

Math.ceil(n)返回大于等于n的最小整数。

Math.round(num)参数num为一个数值,函数结果为num四舍五入后的整数。

因此可以用以上函数配合实现取1-6的随机数:

1,用Math.ceil(Math.random()*6)时,主要获取1到6的随机整数,取0的几率极小。

2,用Math.round(Math.random()*5 + 1),可基本均衡获取1到6的随机整数,其中获取最小值0和最大值6的几率少一半。

3,用Math.floor(Math.random()*6 + 1)时,可均衡获取1到6的随机整数。

使用Math.floor(Math.random()*10+1)函数实现。

1、floor():返回小于等于x的最大整数。

2、函数返回一个浮点,  伪随机数在范围[0,1),也就是说,从0(包括0)往上,但是不包括1(排除1)。实现将初始种子选择到随机数生成算法,它不能被用户选择或重置。

实例演示如下:

1、html代码如下,绑定生成函数:

2、函数代码如下:

2、随机演示效果如下:均为1-10之内的整数。

扩展资料:

生成不重复的10个随机数,可以用数组存储已经生成的数,新生成的数据若不在数组中就满足条件。

1、函数代码如下:

2、同理,绑定一个button用于测试:

2、演示:点击按钮直到产生10个数字。一次随机数据生产如下:(10个不重复)

参考资料:

百度百科--math.random()