有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
重要的
The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.如果你想得到一个介于1(且只有1)和6之间的随机整数,你可以计算:
const rndInt=数学地板(Math.random()*6)+1控制台日志(rndInt)
哪里:
1是起始编号6是可能结果的数量(1+start(6)-end(1))
其他回答
尝试使用:
函数随机(最小值,最大值){return Math.round((Math.random()*(Math.abs(max-min)))+min);}console.log(随机(1,6));
我在搜索用TypeScript编写的随机数生成器,在阅读了所有答案后,我写了这个,希望它对TypeScript程序员有用。
Rand(min: number, max: number): number {
return (Math.random() * (max - min + 1) | 0) + min;
}
获取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))
根据@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
范围[a,b]内的加密强随机整数(假设:a<b)
let rand=(a,b)=>a+(b-a+1)*crypto.getRandomValues(新Uint32Array(1))[0]/2**32|0console.log(兰特(1,6));