- 时间:2021-08-27 06:13 编辑: 来源: 阅读:
- 扫一扫,手机访问
摘要:使用js Math.random()函数生成n到m间的随机数字
摘要:
本文讲解如何使用js生成n到m间的随机数字,主要目的是为后期的js生成验证码做准备。
Math.random()函数返回0和1之间的伪随机数,可能为0,但总是小于1,[0,1)
生成n-m,包含n但不包含m的整数:
第一步算出 m-n的值,假设等于w
第二步Math.random()*w
第三步Math.random()*w+n
第四步parseInt(Math.random()*w+n, 10)
生成n-m,不包含n但包含m的整数:
第一步算出 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
[url=http://tools.jb51.net/aideddesign/suijishu]http://tools.jb51.net/aideddesign/suijishu[/url]
[b]高强度密码生成器:
[/b][url=http://tools.jb51.net/password/CreateStrongPassword]http://tools.jb51.net/password/CreateStrongPassword[/url]