如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
所有这些解决方案都使用了太多的火力。您只需要调用一个函数:Math.random();
Math.random() * max | 0;
这将返回一个介于0(包含)和max(非包含)之间的随机整数。
其他回答
以下是排字的解决方案
function getRandomInt(min:number, max:number):number {
return min+Math.round(Math.random() * (max-min));
}
for(let i:number=0; i<100; i++){
console.log(`${i+1} >> ${getRandomInt(1,6)}`)
}
我制作了这个函数,它考虑了min、max、exclude(要排除的整数列表)和seed(如果您需要种子随机生成器)等选项。
get_random_int = function(args={})
{
let def_args =
{
min: 0,
max: 1,
exclude: false,
seed: Math.random
}
args = Object.assign(def_args, args)
let num = Math.floor(args.seed() * (args.max - args.min + 1) + args.min)
if(args.exclude)
{
let diff = args.max - args.min
let n = num
for(let i=0; i<diff*2; i++)
{
if(args.exclude.includes(n))
{
if(n + 1 <= args.max)
{
n += 1
}
else
{
n = args.min
}
}
else
{
num = n
break
}
}
}
return num
}
它可以像这样使用:
let n = get_random_int
(
{
min: 0,
max: some_list.length - 1,
exclude: [3, 6, 5],
seed: my_seed_function
}
)
或者更简单地说:
let n = get_random_int
(
{
min: 0,
max: some_list.length - 1
}
)
然后您可以执行以下操作:
let item = some_list[n]
主旨:https://gist.github.com/madprops/757deb000bdec25776d5036dae58ee6e
您可以使用此代码段,
let randomNumber = function(first, second) {
let number = Math.floor(Math.random()*Math.floor(second));
while(number < first) {
number = Math.floor(Math.random()*Math.floor(second));
}
return number;
}
下面是JavaScript中Random类的Microsoft.NET实现-
var Random = (function () {
function Random(Seed) {
if (!Seed) {
Seed = this.milliseconds();
}
this.SeedArray = [];
for (var i = 0; i < 56; i++)
this.SeedArray.push(0);
var num = (Seed == -2147483648) ? 2147483647 : Math.abs(Seed);
var num2 = 161803398 - num;
this.SeedArray[55] = num2;
var num3 = 1;
for (var i_1 = 1; i_1 < 55; i_1++) {
var num4 = 21 * i_1 % 55;
this.SeedArray[num4] = num3;
num3 = num2 - num3;
if (num3 < 0) {
num3 += 2147483647;
}
num2 = this.SeedArray[num4];
}
for (var j = 1; j < 5; j++) {
for (var k = 1; k < 56; k++) {
this.SeedArray[k] -= this.SeedArray[1 + (k + 30) % 55];
if (this.SeedArray[k] < 0) {
this.SeedArray[k] += 2147483647;
}
}
}
this.inext = 0;
this.inextp = 21;
Seed = 1;
}
Random.prototype.milliseconds = function () {
var str = new Date().valueOf().toString();
return parseInt(str.substr(str.length - 6));
};
Random.prototype.InternalSample = function () {
var num = this.inext;
var num2 = this.inextp;
if (++num >= 56) {
num = 1;
}
if (++num2 >= 56) {
num2 = 1;
}
var num3 = this.SeedArray[num] - this.SeedArray[num2];
if (num3 == 2147483647) {
num3--;
}
if (num3 < 0) {
num3 += 2147483647;
}
this.SeedArray[num] = num3;
this.inext = num;
this.inextp = num2;
return num3;
};
Random.prototype.Sample = function () {
return this.InternalSample() * 4.6566128752457969E-10;
};
Random.prototype.GetSampleForLargeRange = function () {
var num = this.InternalSample();
var flag = this.InternalSample() % 2 == 0;
if (flag) {
num = -num;
}
var num2 = num;
num2 += 2147483646.0;
return num2 / 4294967293.0;
};
Random.prototype.Next = function (minValue, maxValue) {
if (!minValue && !maxValue)
return this.InternalSample();
var num = maxValue - minValue;
if (num <= 2147483647) {
return parseInt((this.Sample() * num + minValue).toFixed(0));
}
return this.GetSampleForLargeRange() * num + minValue;
};
Random.prototype.NextDouble = function () {
return this.Sample();
};
Random.prototype.NextBytes = function (buffer) {
for (var i = 0; i < buffer.length; i++) {
buffer[i] = this.InternalSample() % 256;
}
};
return Random;
}());
Use:
var r = new Random();
var nextInt = r.Next(1, 100); // Returns an integer between range
var nextDbl = r.NextDouble(); // Returns a random decimal
我想用一个例子来解释:
函数在JavaScript中生成5到25范围内的随机整数
概述:(i) 首先将其转换为范围-从0开始。(ii)然后将其转换为所需的范围(然后将非常易于完成)。
所以基本上,如果你想生成从5到25的随机整数,那么:
第一步:将其转换为范围-从0开始
从“max”和“min”中减去“lower/minimum number”。即
(5-5) - (25-5)
因此,范围将为:
0-20 ...正确的
第二步
现在,如果您希望两个数字都包含在范围内,即“0和20”,则公式为:
数学方程式:Math.floor((Math.random()*21))
一般公式:Math.floor((Math.random()*(max min+1)))
现在,如果我们将减去的/最小的数字(即5)添加到范围中,那么我们可以自动获得0到20的范围=>5到25
第三步
现在将减去的差值加在等式(即5)中,并将“Math.floor”添加到整个等式中:
数学方程式:Math.floor((Math.random()*21)+5)
一般公式:Math.floor((Math.random()*(max-min+1))+min)
因此,最终函数将是:
function randomRange(min, max) {
return Math.floor((Math.random() * (max - min + 1)) + min);
}
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 使用该集合的原因。种子功能
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 将整数转换为字符串,以逗号表示千
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?