在JavaScript中生成两个数字之间的随机数

时间:2022-06-19 14:18:07

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?

是否有方法在指定范围内生成随机数(例如:1、2、3、4、5或6)?

17 个解决方案

#1


1508  

If you wanted to get between 1 and 6, you would calculate:

如果你想在1到6之间,你会计算

Math.floor(Math.random() * 6) + 1  

Where:

地点:

  • 1 is the start number
  • 1是起始数
  • 6 is the number of possible results (1 + start (6) - end (1))
  • 6是可能的结果数(1 + start (6) - end (1))

#2


1638  

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

What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.

它所做的“额外”是允许不以1开头的随机间隔。你可以得到一个从10到15的随机数。的灵活性。

#3


179  

Math.random()

From the Mozilla Developer Network documentation:

Mozilla开发人员网络文档:

// Returns a random integer between min (include) and max (include)

Math.floor(Math.random() * (max - min + 1)) + min;

Useful examples:

有用的例子:

// 0 -> 10
Math.floor(Math.random() * 11);

// 1 -> 10
Math.floor(Math.random() * 10) + 1;

// 5 -> 20
Math.floor(Math.random() * 16) + 5;

// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;

#4


75  

Other solutions:

其他的解决方案:

  • (Math.random() * 6 | 0) + 1
  • (Math.random() * 6 |) + 1
  • ~~(Math.random() * 6) + 1
  • ~~(Math.random() * 6) + 1

#5


28  

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1); that is, from 0 (inclusive) up to but not including 1 (exclusive)

函数的作用是:返回一个浮点数,伪随机数在范围[0,1];也就是说,从0(含)到但不包括1(唯一)

Let's add the min randomly from 0 to max-min

我们把最小值从0随机加到max-min。

Case 0

min + 0 * (max-min) = min

min + 0 * (max-min) = min

Case 1

min + 1 * (max-min) = max

min + 1 * (max-min) = max

Random Case using Math.random 0 <= r < 1

min + r * (max-min) = X, where X has range of min <= X < max

min + r * (max-min) = X,其中X的取值范围为min <= X < max

The above result X is a random numeric. However due to Math.random() our left bound is inclusive, and the right bound is exclusive. To include our right bound we increase the right bound by 1 and floor the result.

上面的结果X是一个随机数字。但是由于Math.random()我们的左绑定是包含的,并且右绑定是独占的。为了包含右边界,我们将右边界增加1,并将结果设为下限。

function generateRandomInteger(min, max) {
  return Math.floor(min + Math.random()*(max+1 - min))
}

To get the random number

generateRandomInteger(-20, 20);

20 generateRandomInteger(-20);

#6


15  

var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;

#7


14  

Or, in Underscore

或者,在强调

_.random(min, max)

#8


13  

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

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

Random Integer: to get a random integer between min and max, use the following code

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

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

Random Floating Point Number: to get a random floating point number between min and max, use the following code

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

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

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

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

#9


11  

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.

当然,您还可以添加一些验证,以确保您不会使用除数字以外的其他方法进行操作。还要确保最小值总是小于或等于最大值。

#10


6  

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.

固定的版本。

#11


3  

Example

例子

Return a random number between 1 and 10:

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

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

The result could be: 3

结果可能是:3

Try yourself: here

试着自己:这里

--

- - -

or using lodash / undescore:

或使用lodash / undescore:

_.random(min, max)

_。随机(最小,最大)

Docs: - lodash - undescore

文档:- lodash - undescore

#12


2  

I was searching random number generator written in TypeScript and I have written this after reading all of the answers, hope It would work for TypeScript coders.

我正在搜索用打印稿编写的随机数生成器,在阅读完所有答案后,我写了这篇文章,希望它对打字稿编码器有用。

    Rand(min: number, max: number): number {
        return (Math.random() * (max - min + 1) | 0) + min;
    }   

#13


2  

Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths.

尽管有很多答案和几乎相同的结果。我想补充我的答案,并解释它的作用。因为理解它的工作原理而不是复制粘贴一行代码是很重要的。生成随机数只不过是简单的数学。

CODE:

代码:

function getR(lower, upper) {

  var percent = (Math.random() * 100);
  // this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
  //now you have a percentage, use it find out the number between your INTERVAL :upper-lower 
  var num = ((percent * (upper - lower) / 100));
  //num will now have a number that falls in your INTERVAL simple maths
  num += lower;
  //add lower to make it fall in your INTERVAL
  //but num is still in decimal
  //use Math.floor>downward to its nearest integer you won't get upper value ever
  //use Math.ceil>upward to its nearest integer upper value is possible
  //Math.round>to its nearest integer 2.4>2 2.5>3   both lower and upper value possible
  console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}

#14


0  

Sense you need to add 1 to the max number, and then subtract the minimum number for any of this to work, and I need to make a lot of random Integers, this function works.

你需要把1加到最大值,然后减去其中任何一个的最小值,我需要做很多随机整数,这个函数可以。

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

This works with both negative, and positive numbers, and I'm working on decimals for a library.

这对负数和正数都有效,我正在为库做小数运算。

#15


0  

Instead of Math.random(), you can use crypto.getRandomValues() to generate evenly-distributed cryptographically-secure random numbers. Here's an example:

与Math.random()不同,您可以使用crypto.getRandomValues()生成均匀分布的加密安全随机数。这里有一个例子:

function randInt(min, max) {
  var MAX_UINT32 = 0xFFFFFFFF;
  var range = max - min;

  if (!(range <= MAX_UINT32)) {
    throw new Error(
      "Range of " + range + " covering " + min + " to " + max + " is > " +
      MAX_UINT32 + ".");
  } else if (min === max) {
    return min;
  } else if (!(max > min)) {
    throw new Error("max (" + max + ") must be >= min (" + min + ").");
  }

  // We need to cut off values greater than this to avoid bias in distribution
  // over the range.
  var maxUnbiased = MAX_UINT32 - ((MAX_UINT32 + 1) % (range + 1));

  var rand;
  do {
    rand = crypto.getRandomValues(new Uint32Array(1))[0];
  } while (rand > maxUnbiased);

  var offset = rand % (range + 1);
  return min + offset;
}

console.log(randInt(-8, 8));          // -2
console.log(randInt(0, 0));           // 0
console.log(randInt(0, 0xFFFFFFFF));  // 944450079
console.log(randInt(-1, 0xFFFFFFFF));
// Uncaught Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295.
console.log(new Array(24).fill().map(n => randInt(8, 12)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9,
//  11, 8, 11, 8, 8, 8, 11, 9, 10, 12, 9, 11]
console.log(randInt(10, 8));
// Uncaught Error: max (8) must be >= min (10).

#16


-5  

I found Francisc's solution above did not include the min or max number in the results, so I altered it like this:

我发现上面的Francisc的解决方案不包括结果中的最小值或最大值,所以我这样修改了:

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

#17


-5  

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

#1


1508  

If you wanted to get between 1 and 6, you would calculate:

如果你想在1到6之间,你会计算

Math.floor(Math.random() * 6) + 1  

Where:

地点:

  • 1 is the start number
  • 1是起始数
  • 6 is the number of possible results (1 + start (6) - end (1))
  • 6是可能的结果数(1 + start (6) - end (1))

#2


1638  

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

What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.

它所做的“额外”是允许不以1开头的随机间隔。你可以得到一个从10到15的随机数。的灵活性。

#3


179  

Math.random()

From the Mozilla Developer Network documentation:

Mozilla开发人员网络文档:

// Returns a random integer between min (include) and max (include)

Math.floor(Math.random() * (max - min + 1)) + min;

Useful examples:

有用的例子:

// 0 -> 10
Math.floor(Math.random() * 11);

// 1 -> 10
Math.floor(Math.random() * 10) + 1;

// 5 -> 20
Math.floor(Math.random() * 16) + 5;

// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;

#4


75  

Other solutions:

其他的解决方案:

  • (Math.random() * 6 | 0) + 1
  • (Math.random() * 6 |) + 1
  • ~~(Math.random() * 6) + 1
  • ~~(Math.random() * 6) + 1

#5


28  

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1); that is, from 0 (inclusive) up to but not including 1 (exclusive)

函数的作用是:返回一个浮点数,伪随机数在范围[0,1];也就是说,从0(含)到但不包括1(唯一)

Let's add the min randomly from 0 to max-min

我们把最小值从0随机加到max-min。

Case 0

min + 0 * (max-min) = min

min + 0 * (max-min) = min

Case 1

min + 1 * (max-min) = max

min + 1 * (max-min) = max

Random Case using Math.random 0 <= r < 1

min + r * (max-min) = X, where X has range of min <= X < max

min + r * (max-min) = X,其中X的取值范围为min <= X < max

The above result X is a random numeric. However due to Math.random() our left bound is inclusive, and the right bound is exclusive. To include our right bound we increase the right bound by 1 and floor the result.

上面的结果X是一个随机数字。但是由于Math.random()我们的左绑定是包含的,并且右绑定是独占的。为了包含右边界,我们将右边界增加1,并将结果设为下限。

function generateRandomInteger(min, max) {
  return Math.floor(min + Math.random()*(max+1 - min))
}

To get the random number

generateRandomInteger(-20, 20);

20 generateRandomInteger(-20);

#6


15  

var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;

#7


14  

Or, in Underscore

或者,在强调

_.random(min, max)

#8


13  

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

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

Random Integer: to get a random integer between min and max, use the following code

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

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

Random Floating Point Number: to get a random floating point number between min and max, use the following code

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

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

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

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

#9


11  

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.

当然,您还可以添加一些验证,以确保您不会使用除数字以外的其他方法进行操作。还要确保最小值总是小于或等于最大值。

#10


6  

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.

固定的版本。

#11


3  

Example

例子

Return a random number between 1 and 10:

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

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

The result could be: 3

结果可能是:3

Try yourself: here

试着自己:这里

--

- - -

or using lodash / undescore:

或使用lodash / undescore:

_.random(min, max)

_。随机(最小,最大)

Docs: - lodash - undescore

文档:- lodash - undescore

#12


2  

I was searching random number generator written in TypeScript and I have written this after reading all of the answers, hope It would work for TypeScript coders.

我正在搜索用打印稿编写的随机数生成器,在阅读完所有答案后,我写了这篇文章,希望它对打字稿编码器有用。

    Rand(min: number, max: number): number {
        return (Math.random() * (max - min + 1) | 0) + min;
    }   

#13


2  

Inspite of many answers and almost same result. I would like to add my answer and explain its working. Because it is important to understand its working rather than copy pasting one line code. Generating random numbers is nothing but simple maths.

尽管有很多答案和几乎相同的结果。我想补充我的答案,并解释它的作用。因为理解它的工作原理而不是复制粘贴一行代码是很重要的。生成随机数只不过是简单的数学。

CODE:

代码:

function getR(lower, upper) {

  var percent = (Math.random() * 100);
  // this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
  //now you have a percentage, use it find out the number between your INTERVAL :upper-lower 
  var num = ((percent * (upper - lower) / 100));
  //num will now have a number that falls in your INTERVAL simple maths
  num += lower;
  //add lower to make it fall in your INTERVAL
  //but num is still in decimal
  //use Math.floor>downward to its nearest integer you won't get upper value ever
  //use Math.ceil>upward to its nearest integer upper value is possible
  //Math.round>to its nearest integer 2.4>2 2.5>3   both lower and upper value possible
  console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}

#14


0  

Sense you need to add 1 to the max number, and then subtract the minimum number for any of this to work, and I need to make a lot of random Integers, this function works.

你需要把1加到最大值,然后减去其中任何一个的最小值,我需要做很多随机整数,这个函数可以。

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

This works with both negative, and positive numbers, and I'm working on decimals for a library.

这对负数和正数都有效,我正在为库做小数运算。

#15


0  

Instead of Math.random(), you can use crypto.getRandomValues() to generate evenly-distributed cryptographically-secure random numbers. Here's an example:

与Math.random()不同,您可以使用crypto.getRandomValues()生成均匀分布的加密安全随机数。这里有一个例子:

function randInt(min, max) {
  var MAX_UINT32 = 0xFFFFFFFF;
  var range = max - min;

  if (!(range <= MAX_UINT32)) {
    throw new Error(
      "Range of " + range + " covering " + min + " to " + max + " is > " +
      MAX_UINT32 + ".");
  } else if (min === max) {
    return min;
  } else if (!(max > min)) {
    throw new Error("max (" + max + ") must be >= min (" + min + ").");
  }

  // We need to cut off values greater than this to avoid bias in distribution
  // over the range.
  var maxUnbiased = MAX_UINT32 - ((MAX_UINT32 + 1) % (range + 1));

  var rand;
  do {
    rand = crypto.getRandomValues(new Uint32Array(1))[0];
  } while (rand > maxUnbiased);

  var offset = rand % (range + 1);
  return min + offset;
}

console.log(randInt(-8, 8));          // -2
console.log(randInt(0, 0));           // 0
console.log(randInt(0, 0xFFFFFFFF));  // 944450079
console.log(randInt(-1, 0xFFFFFFFF));
// Uncaught Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295.
console.log(new Array(24).fill().map(n => randInt(8, 12)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9,
//  11, 8, 11, 8, 8, 8, 11, 9, 10, 12, 9, 11]
console.log(randInt(10, 8));
// Uncaught Error: max (8) must be >= min (10).

#16


-5  

I found Francisc's solution above did not include the min or max number in the results, so I altered it like this:

我发现上面的Francisc的解决方案不包括结果中的最小值或最大值,所以我这样修改了:

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

#17


-5  

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