有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
获取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 randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNum(1, 6);
数学不是我的强项,但我一直在做一个项目,我需要在正负之间生成很多随机数。
function randomBetween(min, max) {
if (min < 0) {
return min + Math.random() * (Math.abs(min)+max);
}else {
return min + Math.random() * max;
}
}
例如
randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)
当然,您也可以添加一些验证,以确保您不使用数字以外的任何内容。还要确保最小值始终小于或等于最大值。
如果您想覆盖负数和正数,并确保其安全,请使用以下方法:
JS解决方案:
function generateRangom(low, up) {
const u = Math.max(low, up);
const l = Math.min(low, up);
const diff = u - l;
const r = Math.floor(Math.random() * (diff + 1)); //'+1' because Math.random() returns 0..0.99, it does not include 'diff' value, so we do +1, so 'diff + 1' won't be included, but just 'diff' value will be.
return l + r; //add the random number that was selected within distance between low and up to the lower limit.
}
Java解决方案:
public static int generateRandom(int low, int up) {
int l = Math.min(low, up);
int u = Math.max(low, up);
int diff = u - l;
int r = (int) Math.floor(Math.random() * (diff + 1)); // '+1' because Math.random() returns 0..0.99, it does not include 'diff' value, so we do +1, so 'diff + 1' won't be included, but just 'diff' value will be.
return l + r;//add the random number that was selected within distance between low and up to the lower limit.
}
这已经晚了九年,但randojs.com让这成为了一个简单的一行:
rando(1, 6)
您只需要将其添加到html文档的头部,就可以轻松地使用随机性做任何事情。数组中的随机值、随机jquery元素、对象中的随机财产,甚至在需要时防止重复。
<script src="https://randojs.com/1.0.0.js"></script>
ES6/Arrow函数版本基于Francis的代码(即顶级答案):
const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);