如何引用js文件加随机数

JavaScript012

如何引用js文件加随机数,第1张

一般写程序的沟通能力都很差,基本上就是往码农方向发展的!没前途的

比如你!

不过我可以揣摩下你的意思!

result=''

function rand(x,y){

for(i=0i<9i++)

result+=Math.floor(Math.random()*(y-x+1))+x

return result

}

保存为 rand.js

调用的时候x为下限,y为上限,生成9个随机数字

在写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