有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
基本上像骰子一样返回1-6,
return Math.round(Math.random() * 5 + 1);
其他回答
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
获取0到400之间的随机整数
let rand=数学舍入(Math.random()*400)document.write(兰特)
获取200到1500之间的随机整数
让范围={min:200,max:1500}设delta=范围.max-范围.minconst rand=数学舍入(range.min+Math.random()*delta)document.write(兰特)
使用函数
函数randBetween(最小值,最大值){设delta=最大值-最小值return Math.round(min+Math.random()*delta)}document.write(randBetween(10,15));
//JavaScript ES6箭头函数常量randBetween=(最小值,最大值)=>{设delta=最大值-最小值return Math.round(min+Math.random()*delta)}document.write(randBetween(10,20))
尽管有许多答案,但结果几乎相同。我想补充一下我的答案并解释一下它的作用。因为理解它的工作方式比复制粘贴单行代码更重要。生成随机数只是简单的数学。
代码:
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));
}
范围[a,b]内的加密强随机整数(假设:a<b)
let rand=(a,b)=>a+(b-a+1)*crypto.getRandomValues(新Uint32Array(1))[0]/2**32|0console.log(兰特(1,6));
简短回答:使用简单的数组即可实现。
您可以在数组元素内交替。
即使您的值不是连续的,此解决方案也有效。值甚至不必是数字。
let array = [1, 2, 3, 4, 5, 6];
const randomValue = array[Math.floor(Math.random() * array.length)];