有没有一种方法可以在JavaScript中生成指定范围内的随机数(例如1到6:1、2、3、4、5或6)?
在JavaScript中生成两个数字之间的随机数
This is about nine years late, but randojs.com makes this a simple one-liner:
rando(1, 6)
You just need to add this to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.
<script src="https://randojs.com/1.0.0.js"></script>
to return 1-6 like a dice basically, return Math.round(Math.random() * 5 + 1);
I discovered a great new way to do this using ES6 default parameters. It is very nifty since it allows either one argument or two arguments. Here it is:
function random(n, b = 0) {
return Math.random() * (b-n) + n;
}
This should work:
const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
I was searching random number generator written in TypeScript and I have written this after reading all of the answers, hope It would work for TypeScript coders.
Rand(min: number, max: number): number {
return (Math.random() * (max - min + 1) | 0) + min;
}
Crypto-strong random integer number in range [a,b] (assumption: a < b )
let rand= (a,b)=> a+(b-a+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0
console.log( rand(1,6) );
jsfiddle:https ://jsfiddle.net/cyGwf/477/
随机整数:要获取min
和之间的随机整数max
,请使用以下代码
function getRandomInteger(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
随机浮点数:要获取min
和之间的随机浮点数max
,请使用以下代码
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;
或者,在下划线
_.random(min, max)
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
它“额外”的作用是允许以1开头的随机间隔。因此,例如,您可以获得10到15之间的随机数。灵活性。
Math.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 Crypto API,更确切地说,使用window.crypto.getRandomValues()方法。
重要
以下代码仅在最小值为时才有效1
。不适用于除以外的最小值1
。
如果要获得1(且只有1)和6 之间的随机整数,则应计算:
Math.floor(Math.random() * 6) + 1
哪里:
- 1是起始号码
- 6是可能的结果数(1 +开始(6) -结束(1))
Try using: