2016-11-25 80 views
1

我需要一個從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

您需要減少獲得正確間隔的因子。

y = Math.floor(Math.random() * (max - min)) + min; 
//       ^ ^^^^^^ 
相關問題