Generate random number between two numbers in JavaScript

后端 未结 23 2055
走了就别回头了
走了就别回头了 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:24

    Math is not my strong point, but I've been working on a project where I needed to generate a lot of random numbers between both positive and negative.

    function randomBetween(min, max) {
        if (min < 0) {
            return min + Math.random() * (Math.abs(min)+max);
        }else {
            return min + Math.random() * max;
        }
    }
    

    E.g

    randomBetween(-10,15)//or..
    randomBetween(10,20)//or...
    randomBetween(-200,-100)
    

    Of course, you can also add some validation to make sure you don't do this with anything other than numbers. Also make sure that min is always less than or equal to max.

提交回复
热议问题