-1

我尝试从一组可能的值中随机输出一些数字。

我遇到的问题是递归,因此如果该数字已被使用(并且不再在可能值的数组中),则我的函数检查随机生成的数字是否已在之前再次开始使用。

我得到一个我也不明白的无限循环。

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
    // Global array of possible numbers
    var possibleNumbers = [1, 2, 3, 4];

    // Check if element in the array
    function inArray(needle, haystack) {
        var length = haystack.length;
        for(var i = 0; i < length; i++) {
            if(haystack[i] == needle) return true;
        }
        return false;
    }

    // Random number between 1 and 4
    function genRand(){return Math.floor(1+ (4 * Math.random()));}

    // Return an random number from the possible numbers in the global array
    function randNumFromArray() {
        var generatedNum = genRand();
        console.log('possibleNumbers so far:' + possibleNumbers);
        console.log('generatedNum: ' + generatedNum);

        // Restart as long as the number is not in the array (not already used)
        while(inArray(generatedNum,possibleNumbers) === false) {
            console.log('Generating again...');
            randNumFromArray();
        }

        console.log('generatedNum not used yet, using it');

        // Use that number and remove it from the array
        var index = possibleNumbers.indexOf(generatedNum);
        if (index > -1) {
            possibleNumbers.splice(index, 1);
        }

        console.log('Removing the number from the array');
        console.log('possibleNumbers after removal:' + possibleNumbers);
        return generatedNum;
    }

    // Calling the function 4 times to get the 4 possible numbers in a random order 
    randNumFromArray();
    randNumFromArray();
    randNumFromArray();
    randNumFromArray();
</script>
</head>
<body>
</body>
</html>
4

1 回答 1

0

让我们调试你的代码,

  1. Math.random() // Returns a random number between 0 (inclusive) and 1 (exclusive)

  2. 4 * Math.random() // will be number either be 0 or 4 < number < 5.

  3. 1+ (4 * Math.random()) // In your Case you are probably waiting for Math.random() to generate 0 which of least probability (because any number other than zero will make the total sum to 5.xx)

  4. Math.floor(1+ (4 * Math.random()) // will surely not be in your list [1, 2, 3, 4]; if number generate > 0 then will cross 4 so It will loop continuously

如果要生成特定范围的随机数,请使用,

/**
 * Returns a random number between min and max
 */
function getRandomArbitary (min, max) {
    return Math.random() * (max - min) + min;
}

参考生成特定范围的随机数

于 2013-09-25T13:28:45.267 回答