美文网首页Web前端之路让前端飞
js 取x到y之间的随机数(包含解析)

js 取x到y之间的随机数(包含解析)

作者: 李佳明先生 | 来源:发表于2019-10-30 20:03 被阅读0次
function random(x,y) {
        return Math.floor(y-Math.random()*(y-x))
    }

函数使用条件:y>x;

函数随机结果:结果>=x && 结果<=y;

例如:
console.log(random(1,3));

则随机结果总在1和3之间(包含1,包含3);

到这里急用的话就可以ctrl c ctrl v了,以下是深入了解阶段

解析:

蓝色区域代表y的长度;
红色区域代表y-x的长度;

先理解Math.random()*(y-x)Math.random()大家都知道,取的是0到1之间的数字(包含0,不包含1)

那咱们可以想象Math.random()*(y-x)的两个极端值为0*(y-x)0.999999999(无限循环下去)*(y-x),取两个极端值的结果,代入式子;

即:

最大值:

Math.floor(y-Math.random()*(y-x))

Math.floor(y-0*(y-x))

Math.floor(y-0)

Math.floor(y)

=y;

最小值:

Math.floor(y-Math.random()*(y-x))

Math.floor(y-0.999999999(无限循环下去)*(y-x))

Math.floor(蓝色区域-0.999999999(无限循环下去)*红色区域)

Math.floor(蓝色区域-无限接近于红色区域)

经过Math.floor向下取整后后最小为x;

相关文章

网友评论

    本文标题:js 取x到y之间的随机数(包含解析)

    本文链接:https://www.haomeiwen.com/subject/ustavctx.html