Home  >  Q&A  >  body text

javascript生成随机数的问题?

生成1-3的随机数是这样的

slotOne = Math.floor(Math.random() * (3 - 1 + 1)) + 1;

(3 -1 + 1)这个是为什么?就我所知道的,要生成0-n的随机数

Math.floor(Math.random() * n);

所以既然是1-3,应该是

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

希望有大神解释一下...是网站人员的问题,还是有其他的原因...

城堡下的诡洞城堡下的诡洞2764 days ago890

reply all(2)I'll reply

  • 数据分析师

    数据分析师2017-10-01 00:32:37

    Javascript generates random numbers? -PHP Chinese website Q&A-Is there a problem with javascript generating random numbers? -PHP Chinese website Q&A

    Let’s take a look and learn.

    reply
    0
  • 迷茫

    迷茫2017-02-25 09:14:06

    生成一个m~n的随机数,则最小值为m+0,最大值为m+(n-m+1);
    而Math.random()生成的是0~1,故Math.floor(Math.random() * (n - m + 1)) + m 套入1-3就是你要的值

    reply
    1
  • Cancelreply