具有特定范围的随机整数:值大于最大值

时间:2016-11-25 12:23:27

标签: javascript random

我需要一个从100screenHeight - 400的特定范围内的随机整数。

代码如下,但为什么值大于最大值?

for (var i = 0; i < 100; i++) {
    const   screenHeight = $(document).height(),
            max  = screenHeight - 400,
            min  = 100,
            y    = Math.floor(Math.random() * max) + min;

    console.log(max, y, y > max);
}

1 个答案:

答案 0 :(得分:1)

您需要减少获得正确间隔的因素。

 y = Math.floor(Math.random() * (max - min)) + min;
 //                             ^    ^^^^^^
相关问题