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

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


当前回答

我发现了一种使用ES6默认参数实现这一点的新方法。它非常漂亮,因为它允许一个参数或两个参数。这里是:

function random(n, b = 0) {
    return Math.random() * (b-n) + n;
}

其他回答

这个简单的功能很方便,在任何情况下都可以使用(经过充分测试)。此外,结果的分布已经过充分测试,100%正确。

function randomInteger(pMin = 1, pMax = 1_000_000_000)
//Author: Axel Gauffre. 
//Here: https://stackoverflow.com/a/74636954/5171000
//Inspired by: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_number_between_two_values
//
//This function RETURNS A RANDOM INTEGER between pMin (INCLUDED) and pMax (INCLUDED).
//  - pMin and pMax should be integers.
//  - HOWEVER, if pMin and/or pMax are FLOATS, they will be ROUNDED to the NEAREST integer.
//  - NEGATIVE values ARE supported.
//  - The ORDER of the 2 arguments has NO consequence: If pMin > pMax, then pMin and pMax will simply be SWAPPED.
//  - If pMin is omitted, it will DEFAULT TO 1.
//  - If pMax is omitted, it will DEFAULT TO 1 BILLION.
//
//This function works in ANY cases (fully tested).
//Also, the distribution of the results has been fully tested and is 100% correct.
{
    pMin = Math.round(pMin);
    pMax = Math.round(pMax);
    if (pMax < pMin) { let t = pMin; pMin = pMax; pMax = t;}
    return Math.floor(Math.random() * (pMax+1 - pMin) + pMin);
}

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

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

这应该是有效的:

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

ES6/Arrow函数版本基于Francis的代码(即顶级答案):

const randomIntFromInterval = (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