两个数字之间的Javascript随机整数

时间:2012-04-13 01:43:13

标签: javascript random

我正在尝试创建一个随机数生成器,在两个数字之间生成随机数。例如,假设我想生成一个介于4到10之间的随机数,我希望它能够从4到10中的任意数字中选择。这是我尝试过的:

var randNumMin = 4;
var randNumMax = 10;
var randInt = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);

然而,这似乎不起作用并产生了不在4到10之间的奇怪随机数,有些从0开始。这样做的正确算法是什么?

以下是我在以下实现算法的代码:

$(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.");
        }

    });
});

我也尝试用这个替换randInt行:

var randInt = Math.floor((Math.random() * ((randNumMax + 1) - randNumMin)) + randNumMin);

它仍然无效。 我不确定算法是错误的还是我将错误合并到函数中。感谢您的回答。

5 个答案:

答案 0 :(得分:51)

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

//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);
}

Generate random number between two numbers in JavaScript

答案 1 :(得分:2)

您的问题是您从未将字符串转换为数字,请尝试添加此

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;

如果值为空字符串以严格相等,则需要更改检查。要查看我的意思,请尝试使用其中一个值的零。 0 == ""//returns true因为两者都是假的0 === ""//returns false

答案 2 :(得分:2)

Underscore.js对此_.random(min,max)

有很好的效用

答案 3 :(得分:1)

这个怎么样?

var max = 10;
var min = 4;
var random = Math.floor((Math.random() * ((max + 1) - min)) + min);

答案 4 :(得分:0)

randojs.com使它成为简单的单行代码:

<script src="https://randojs.com/1.0.0.js"></script>

您只需要将此内容添加到html文档的开头,就可以轻松地随机执行几乎任何您想做的事情。来自数组的随机值,随机的jquery元素,对象的随机属性,甚至在需要时防止重复。



    var i = "reddit/IndicatorFastScroll"; //githubusername/repository

    async function getCommits() {
        //const test = "https://api.github.com/repos/"
        const test = "https://api.github.com/search/commits?q=repo:"
        const testurl = test.concat(i);
        const pvm = " author-date:2000-03-01..2019-12-02"

        const url = testurl.concat(pvm)
        const headers = {
            "Accept" : "application/vnd.github.cloak-preview"
        }
        const response = await fetch(url, {
            "method" : "GET",
            "headers" : headers
        })

        const link = response.headers.get("link")
        const links = link.split(",")
        const urls = links.map(a=> {
            return {
                url: a.split(";")[0].replace(">","").replace("<",""),
                title:a.split(";")[1]
            }
        })
        const result = await response.json()
        result.items.slice(0,10).forEach(i=>{
      //  result.items.forEach(i=>{
            const img = document.createElement("img")
            img.src = i.author.avatar_url;
            img.style.width="32px"
            img.style.height="32px"
            const anchor = document.createElement("a")
            anchor.href = i.html_url;
            anchor.textContent = i.commit.message;
            divResult.appendChild(img)
            divResult.appendChild(anchor)
            divResult.appendChild(document.createElement("br"))
        })
    }
</script>