如何在JavaScript中的两个指定变量之间生成随机整数,例如x=4和y=8将输出4、5、6、7、8中的任意一个?
当前回答
random(min,max)生成介于min(含)和max(不含)之间的随机数Math.floor将数字向下舍入到最接近的整数函数generateRandomInteger(最小,最大){return数学下限(随机(最小值,最大值))}
因此,要生成一个介于4和8之间的随机整数,请使用以下参数调用上述函数:
generateRandomInteger(4, 9)
其他回答
我的生成0和n之间的随机数的方法,其中n<=10(n除外):
Math.floor((Math.random() * 10) % n)
这是我对一个范围内的随机数的看法,就像我想得到一个基数到指数范围内的一个随机数。例如,基数=10,指数=2,理想情况下给出从0到100的随机数,依此类推。
如果它有助于使用它,这里是:
// Get random number within provided base + exponent
// By Goran Biljetina --> 2012
function isEmpty(value) {
return (typeof value === "undefined" || value === null);
}
var numSeq = new Array();
function add(num, seq) {
var toAdd = new Object();
toAdd.num = num;
toAdd.seq = seq;
numSeq[numSeq.length] = toAdd;
}
function fillNumSeq (num, seq) {
var n;
for(i=0; i<=seq; i++) {
n = Math.pow(num, i);
add(n, i);
}
}
function getRandNum(base, exp) {
if (isEmpty(base)) {
console.log("Specify value for base parameter");
}
if (isEmpty(exp)) {
console.log("Specify value for exponent parameter");
}
fillNumSeq(base, exp);
var emax;
var eseq;
var nseed;
var nspan;
emax = (numSeq.length);
eseq = Math.floor(Math.random()*emax) + 1;
nseed = numSeq[eseq].num;
nspan = Math.floor((Math.random())*(Math.random()*nseed)) + 1;
return Math.floor(Math.random()*nspan) + 1;
}
console.log(getRandNum(10, 20), numSeq);
//Testing:
//getRandNum(-10, 20);
//console.log(getRandNum(-10, 20), numSeq);
//console.log(numSeq);
您可以使用此代码段,
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
我制作了这个函数,它考虑了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
推荐文章
- 什么时候JavaScript是同步的?
- 如何在Typescript中解析JSON字符串
- Javascript reduce()在对象
- 在angularJS中& vs @和=的区别是什么
- 错误"Uncaught SyntaxError:意外的标记与JSON.parse"
- JavaScript中的querySelector和querySelectorAll vs getElementsByClassName和getElementById
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- setTimeout带引号和不带括号的区别
- 在JS的Chrome CPU配置文件中,'self'和'total'之间的差异
- 用javascript检查输入字符串中是否包含数字
- 如何使用JavaScript分割逗号分隔字符串?
- 在Javascript中~~(“双波浪号”)做什么?
- 谷歌chrome扩展::console.log()从后台页面?
- 未捕获的SyntaxError: