有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
尽管有许多答案,但结果几乎相同。我想补充一下我的答案并解释一下它的作用。因为理解它的工作方式比复制粘贴单行代码更重要。生成随机数只是简单的数学。
代码:
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));
}
其他回答
数学.随机()
返回介于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()方法。
重要的
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))
我发现了一种使用ES6默认参数实现这一点的新方法。它非常漂亮,因为它允许一个参数或两个参数。这里是:
function random(n, b = 0) {
return Math.random() * (b-n) + n;
}
对于大数字。
var min_num = 900;
var max_num = 1000;
while(true){
let num_random = Math.random()* max_num;
console.log('input : '+num_random);
if(num_random >= min_num){
console.log(Math.floor(num_random));
break;
} else {
console.log(':::'+Math.floor(num_random));
}
}
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;