【问题标题】:Recursion in a while loop in javascriptjavascript中的while循环中的递归
【发布时间】:2013-09-30 23:52:24
【问题描述】:

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

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

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

这是我的代码:

<!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>

【问题讨论】:

    标签: javascript recursion random while-loop infinite-loop


    【解决方案1】:

    让我们调试您的代码,

    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 &lt; number &lt; 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 &gt; 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;
    }
    

    Refer用于生成特定范围的随机数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 2013-08-12
      • 2014-08-23
      • 2016-03-19
      • 2016-02-27
      • 2012-08-04
      • 2021-05-03
      相关资源
      最近更新 更多