有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
尝试使用:
函数随机(最小值,最大值){return Math.round((Math.random()*(Math.abs(max-min)))+min);}console.log(随机(1,6));
其他回答
根据@Francisc的答案中的int版本添加具有固定精度版本的float:
function randomFloatFromInterval (min, max, fractionDigits) {
const fractionMultiplier = Math.pow(10, fractionDigits)
return Math.round(
(Math.random() * (max - min) + min) * fractionMultiplier,
) / fractionMultiplier
}
so:
randomFloatFromInterval(1,3,4) // => 2.2679, 1.509, 1.8863, 2.9741, ...
对于int答案
randomFloatFromInterval(1,3,0) // => 1, 2, 3
ES6/Arrow函数版本基于Francis的代码(即顶级答案):
const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
函数randomIntFromInterval(min,max){//包括min和maxreturn Math.floor(Math.random()*(max-min+1)+min)}常量rndInt=随机IntFromInterval(1,6)控制台日志(rndInt)
它的“额外”之处在于它允许不以1开头的随机间隔。例如,你可以得到一个从10到15的随机数。灵活性
基本上像骰子一样返回1-6,
return Math.round(Math.random() * 5 + 1);
范围[a,b]内的加密强随机整数(假设:a<b)
let rand=(a,b)=>a+(b-a+1)*crypto.getRandomValues(新Uint32Array(1))[0]/2**32|0console.log(兰特(1,6));