我尝试从一组可能的值中随机输出一些数字。
我遇到的问题是递归,因此如果该数字已被使用(并且不再在可能值的数组中),则我的函数检查随机生成的数字是否已在之前再次开始使用。
我得到一个我也不明白的无限循环。
这是我的代码:
<!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>