有没有办法用JavaScript生成指定范围内的随机数?

例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。


当前回答

尝试使用:

函数随机(最小值,最大值){return Math.round((Math.random()*(Math.abs(max-min)))+min);}console.log(随机(1,6));

其他回答

基本上像骰子一样返回1-6,

return Math.round(Math.random() * 5 + 1);

数学不是我的强项,但我一直在做一个项目,我需要在正负之间生成很多随机数。

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

例如

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

当然,您也可以添加一些验证,以确保您不使用数字以外的任何内容。还要确保最小值始终小于或等于最大值。

这应该是有效的:

const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min

jsfiddle:https://jsfiddle.net/cyGwf/477/

随机整数:要获得最小值和最大值之间的随机整数,请使用以下代码

function getRandomInteger(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

随机浮点数:要获得最小值和最大值之间的随机浮点数,请使用以下代码

function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

实例

返回1到10之间的随机数:

Math.floor((Math.random() * 10) + 1);

结果可能是:3.

试试看:这里

--

或使用lodash/descore:

_.随机(最小值,最大值)

文件:-罗达什-不受欢迎的