Generate random number between two numbers in JavaScript

后端 未结 23 2087
走了就别回头了
走了就别回头了 2020-11-22 01:09

Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?

23条回答
  •  臣服心动
    2020-11-22 01:22

    I wrote more flexible function which can give you random number but not only integer.

    function rand(min,max,interval)
    {
        if (typeof(interval)==='undefined') interval = 1;
        var r = Math.floor(Math.random()*(max-min+interval)/interval);
        return r*interval+min;
    }
    
    var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
    var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0
    

    Fixed version.

提交回复
热议问题