有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
有没有办法用JavaScript生成指定范围内的随机数?
例如:指定范围从1到6,随机数可以是1、2、3、4、5或6。
当前回答
范围[a,b]内的加密强随机整数(假设:a<b)
let rand=(a,b)=>a+(b-a+1)*crypto.getRandomValues(新Uint32Array(1))[0]/2**32|0console.log(兰特(1,6));
其他回答
函数randomIntFromInterval(min,max){//包括min和maxreturn Math.floor(Math.random()*(max-min+1)+min)}常量rndInt=随机IntFromInterval(1,6)控制台日志(rndInt)
它的“额外”之处在于它允许不以1开头的随机间隔。例如,你可以得到一个从10到15的随机数。灵活性
这已经晚了九年,但randojs.com让这成为了一个简单的一行:
rando(1, 6)
您只需要将其添加到html文档的头部,就可以轻松地使用随机性做任何事情。数组中的随机值、随机jquery元素、对象中的随机财产,甚至在需要时防止重复。
<script src="https://randojs.com/1.0.0.js"></script>
根据@Francisc的答案中的int版本添加具有固定精度版本的float:
function randomFloatFromInterval (min, max, fractionDigits) {
const fractionMultiplier = Math.pow(10, fractionDigits)
return Math.round(
(Math.random() * (max - min) + min) * fractionMultiplier,
) / fractionMultiplier
}
so:
randomFloatFromInterval(1,3,4) // => 2.2679, 1.509, 1.8863, 2.9741, ...
对于int答案
randomFloatFromInterval(1,3,0) // => 1, 2, 3
我发现了一种使用ES6默认参数实现这一点的新方法。它非常漂亮,因为它允许一个参数或两个参数。这里是:
function random(n, b = 0) {
return Math.random() * (b-n) + n;
}
这个简单的功能很方便,在任何情况下都可以使用(经过充分测试)。此外,结果的分布已经过充分测试,100%正确。
function randomInteger(pMin = 1, pMax = 1_000_000_000)
//Author: Axel Gauffre.
//Here: https://stackoverflow.com/a/74636954/5171000
//Inspired by: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_number_between_two_values
//
//This function RETURNS A RANDOM INTEGER between pMin (INCLUDED) and pMax (INCLUDED).
// - pMin and pMax should be integers.
// - HOWEVER, if pMin and/or pMax are FLOATS, they will be ROUNDED to the NEAREST integer.
// - NEGATIVE values ARE supported.
// - The ORDER of the 2 arguments has NO consequence: If pMin > pMax, then pMin and pMax will simply be SWAPPED.
// - If pMin is omitted, it will DEFAULT TO 1.
// - If pMax is omitted, it will DEFAULT TO 1 BILLION.
//
//This function works in ANY cases (fully tested).
//Also, the distribution of the results has been fully tested and is 100% correct.
{
pMin = Math.round(pMin);
pMax = Math.round(pMax);
if (pMax < pMin) { let t = pMin; pMin = pMax; pMax = t;}
return Math.floor(Math.random() * (pMax+1 - pMin) + pMin);
}