Javascript 两个数字之间的Javascript随机整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10134237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Random Integer Between two Numbers
提问by Hyman Davis
I'm trying to create a random number generator that generates random numbers between two numbers. For instance, let's say I want to generate a random number between 4 and 10, I would want it to be able to choose from any number from 4 - 10. Here is what I tried:
我正在尝试创建一个随机数生成器,用于在两个数字之间生成随机数。例如,假设我想生成一个 4 到 10 之间的随机数,我希望它能够从 4 到 10 之间的任何数字中进行选择。这是我尝试过的:
var randNumMin = 4;
var randNumMax = 10;
var randInt = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
However, that didn't seem to work and generated weird random numbers that weren't between 4 and 10, and some began with 0. What would be the correct algorithm to do this?
但是,这似乎不起作用并生成了不在 4 到 10 之间的奇怪随机数,有些以 0 开头。执行此操作的正确算法是什么?
Here is the code I'm implementing the algorithm in:
这是我正在实现算法的代码:
$(function() {
$('#generateRandNums').click(function() {
var numCount = document.getElementById("randNumCount").value;
var randNumMin = document.getElementById("randNumMin").value;
var randNumMax = document.getElementById("randNumMax").value;
if (numCount.match(/^[\d]*$/ ) && randNumMin.match(/^[\d]*$/ ) && randNumMax.match(/^[\d]*$/ )) {
if (numCount == "" || randNumMin == "" || randNumMax == "") {
alert ("Please fill out all forms then try again.");
} else {
if (randNumMin>randNumMax) {
alert ("Please make sure your first number is smaller than the second, then try again.");
} else {
if (randNumMin<0) {
alert ("Please make sure that you generate a positive number of random numbers, then try again.");
} else {
if (numCount>1) {
var randResult = ("You generated " + numCount + " random numbers between " + randNumMin + " and " + randNumMax + " and got the numbers ")
oneNumber = 0;
} else {
var randResult = ("You generated a random number between " + randNumMin + " and " + randNumMax + " and got the number ");
oneNumber = 1;
}
for (i=0;i<numCount;i++) {
//Get a random number between randNumMin and randNumMax
var randInt = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
if (i == numCount-1) {
if (oneNumber == 0) {
randResult = (randResult + "and " + randInt + ".");
} else {
randResult = (randResult + randInt + ".");
}
} else {
randResult = (randResult + randInt + ", ");
}
}
$("#randNumResults").val(randResult);
}
}
}
} else {
alert ("Make sure you only enter numbers and no spaces, then try again.");
}
});
});
I also tried replacing the randInt line with this:
我也尝试用这个替换 randInt 行:
var randInt = Math.floor((Math.random() * ((randNumMax + 1) - randNumMin)) + randNumMin);
It still didn't work. I'm not sure if the algorithm is wrong or I'm incorporating it wrong into the function. An answer is appreciated, thanks.
它仍然没有奏效。我不确定算法是错误的还是我将它错误地合并到函数中。感谢回答,谢谢。
采纳答案by qw3n
Your problem is you never converted your string to numbers try adding this
你的问题是你从来没有将你的字符串转换为数字尝试添加这个
if ( numCount.match(/^[\d]*$/ ) &&
randNumMin.match(/^[\d]*$/ ) &&
randNumMax.match(/^[\d]*$/ )){
if (numCount === "" || randNumMin === "" || randNumMax === "") {
alert ("Please fill out all forms then try again.");
} else {
numCount=numCount-0;randNumMin=randNumMin-0;randNumMax=randNumMax-0;
Another note you need to change your checking if the value is an empty string to strict equality. To see what I mean try using zero for one of the values. 0 == ""//returns true
because both are falsy 0 === ""//returns false
.
另请注意,您需要将检查值是否为空字符串更改为严格相等。要了解我的意思,请尝试对其中一个值使用零。0 == ""//returns true
因为两者都是假的0 === ""//returns false
。
回答by Ian
Generating random whole numbers in JavaScript in a specific range?
/**
* Returns a random number between min and max
*/
function getRandomArbitary (min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min and max
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
http://roshanbh.com.np/2008/09/get-random-number-range-two-numbers-javascript.html
http://roshanbh.com.np/2008/09/get-random-number-range-two-numbers-javascript.html
//function to get random number upto m
function randomXToY(minVal,maxVal,floatVal)
{
var randVal = minVal+(Math.random()*(maxVal-minVal));
return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}
or
或者
回答by rhigdon
Underscore.jshas a nice utility for this _.random(min,max)
Underscore.js有一个很好的工具为这个_.random(最小值,最大值)
回答by mccambridge
How about this?
这个怎么样?
var max = 10;
var min = 4;
var random = Math.floor((Math.random() * ((max + 1) - min)) + min);
回答by Aaron Plocharczyk
randojs.commakes this a simple one-liner:
randojs.com使这成为一个简单的单行:
rando(4, 10)
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.
您只需要将它添加到您的 html 文档的头部,您就可以轻松地随心所欲地做任何想做的事情。来自数组的随机值、随机的 jquery 元素、来自对象的随机属性,甚至在需要时防止重复。
<script src="https://randojs.com/1.0.0.js"></script>