Javascript非重复数字生成器有时会返回多个数字

时间:2015-06-03 01:42:33

标签: javascript

我试图为最多13个数字创建一个随机非重复数字生成器。当我运行以下函数时,我得到变化输出,这是使用单击按钮运行该函数5次的结果和代码。我无法理解为什么它会重复一些数字。

var checkIfRandom = new Array();



    function getRandom(){
        var randomNum= Math.floor(Math.random()*13);
        if(checkIfRandom.indexOf(randomNum) !== -1){
            getRandom();
    }else if(checkIfRandom.indexOf(randomNum)==-1){
        checkIfRandom.push(randomNum);
    }

        console.log(randomNum);

    };

//results
2 //Click 1
7, 2 //Click 2
6 //Click 3
1 //Click 4 
5,7,1 //Click 5
[2, 7, 6, 1, 5]//After 5 clicks I logged the checkIfRandom array to the console in chrome.

2 个答案:

答案 0 :(得分:1)

您正在使用递归,这意味着它将先前的非唯一数字存储在堆栈中并仍在记录它们。将console.log()移至else if,使其显示为:

function getRandom(){
    var randomNum= Math.floor(Math.random()*13);
    if(checkIfRandom.indexOf(randomNum) !== -1){
        getRandom();
}else if(checkIfRandom.indexOf(randomNum)==-1){
    checkIfRandom.push(randomNum);
    console.log(randomNum);
}
};

答案 1 :(得分:0)

// empty array with size we want
var randomList = new Array(13).join("|").split("|");

function getRandom()
{
    // if "" doesn't exist then every number has been used
    if(randomList.indexOf("") === -1) return -1;

    // get random number
    var randomNum = Math.floor(Math.random() * randomList.length);

    // if its already used then get a new one
    if(randomList[randomNum]) return getRandom();

    // save the random num and return it
    randomList[randomNum] = true;
    return randomNum;
}

http://jsfiddle.net/vpkspna4/

相关问题