有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
对于大数字。
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));
}
}
其他回答
数学.随机()
返回介于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()方法。
jsfiddle:https://jsfiddle.net/cyGwf/477/
随机整数:要获得最小值和最大值之间的随机整数,请使用以下代码
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
随机浮点数:要获得最小值和最大值之间的随机浮点数,请使用以下代码
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
我在搜索用TypeScript编写的随机数生成器,在阅读了所有答案后,我写了这个,希望它对TypeScript程序员有用。
Rand(min: number, max: number): number {
return (Math.random() * (max - min + 1) | 0) + min;
}
我发现了一种使用ES6默认参数实现这一点的新方法。它非常漂亮,因为它允许一个参数或两个参数。这里是:
function random(n, b = 0) {
return Math.random() * (b-n) + n;
}
实例
返回1到10之间的随机数:
Math.floor((Math.random() * 10) + 1);
结果可能是:3.
试试看:这里
--
或使用lodash/descore:
_.随机(最小值,最大值)
文件:-罗达什-不受欢迎的