前言
本文展示了求js随机数的一些常用用法
–
一、基础随机数求法
获取一个 [0,1) 的随机数
var random1 = Math.random()
console.log(random1); //0.15502465163041257
Math.random()方法 得出的是一个大于或者等于0 然后最大可以无限接近于1 不等于1的随机值
所有扩展用法都是基于这个取值范围得到的
二、基础用法扩展
生成 [one, two) 范围内的随机数
function getRandom1(one, two) {
if (one < two) {
return Math.random() * (two - one) + one
} else {
return Math.random() * (one - two) + two
}
}
console.log(getRandom1(2, 4), '<'); // 3.021933876110561 '<'
console.log(getRandom1(4, 2), '>'); // 3.2829077427720192 '>'
生成 (one, two) 范围内的随机数
function getRandom2(one, two) {
if (one < two) {
var data = Math.random() * (two - one) + one
while (data !== one) {
return data
}
return getRandom2(one, two)
} else {
var data = Math.random() * (one - two) + two
while (data !== one) {
return data
}
return getRandom2(one, two)
}
}
console.log(getRandom2(2, 3), '()'); // 2.684042669080733 '()'
三、再扩展
生成指定位数的随机数
代码如下(示例):
function random3(n) {
let Begin = ''
for (let i = 0; i < n; i++) {
Begin += Math.floor(Math.random() * 10)
}
let result = Number(Begin)
return result
}
console.log(random3(9), 'DIYnumber'); // 735140887 'DIYnumber'
可以结合 Math 其他的一些方法 对得到的随机值进行取整等操作