有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
尽管有许多答案,但结果几乎相同。我想补充一下我的答案并解释一下它的作用。因为理解它的工作方式比复制粘贴单行代码更重要。生成随机数只是简单的数学。
代码:
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));
}
其他回答
或者,在Undercore
_.random(min, max)
对于大数字。
var min_num = 900;
var max_num = 1000;
while(true){
let num_random = Math.random()* max_num;
console.log('input : '+num_random);
if(num_random >= min_num){
console.log(Math.floor(num_random));
break;
} else {
console.log(':::'+Math.floor(num_random));
}
}
使用可重用的随机函数。
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNum(1, 6);
函数randomIntFromInterval(min,max){//包括min和maxreturn Math.floor(Math.random()*(max-min+1)+min)}常量rndInt=随机IntFromInterval(1,6)控制台日志(rndInt)
它的“额外”之处在于它允许不以1开头的随机间隔。例如,你可以得到一个从10到15的随机数。灵活性
这个简单的功能很方便,在任何情况下都可以使用(经过充分测试)。此外,结果的分布已经过充分测试,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);
}