有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
如果起始数字是1,如示例(1-6)所示,则可以使用Math.ceil()方法代替Math.floor()。
Math.ceil(Math.random() * 6)
而不是
Math.floor(Math.random() * 6) + 1
我们不要忘记其他有用的数学方法。
其他回答
使用可重用的随机函数。
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomNum(1, 6);
数学.随机()
返回介于min(包含)和max(包含)之间的整数随机数:
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
或介于min(包含)和max(不包含)之间的任意随机数:
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
有用的示例(整数):
// 0 -> 10
Math.floor(Math.random() * 11);
// 1 -> 10
Math.floor(Math.random() * 10) + 1;
// 5 -> 20
Math.floor(Math.random() * 16) + 5;
// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
**总是很高兴被提醒(Mozilla):
Math.random()不提供加密安全的随机数字。不要将它们用于与安全相关的任何事情。使用Web加密API,更准确地说window.crypto.getRandomValues()方法。
这应该是有效的:
const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
尝试使用:
函数随机(最小值,最大值){return Math.round((Math.random()*(Math.abs(max-min)))+min);}console.log(随机(1,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))