I'm trying to shuffle to generate a random number from an array and splice, but keep getting undefined for the last element that's left in the array. Here, I can generate random numbers that do not repeat. Below is the code for the same.
<body>
<div id="bingo">
<script>
let numbers = new Set()
.add("B1")
.add("B2")
.add("B3")
.add("B4")
.add("B5")
.add("B6")
.add("B7")
.add("B8")
.add("B9")
.add("B10");
let called = Array.from(numbers);
let display = new Array();
function getRandomNum()
{
function rando()
{
for (let i = called.length - 1; i > 0; i++)
{
const j = Math.floor(Math.random() * called.length);
const number = called[i];
called[i] = called[j];
called[j] = number;
if(number)
{
called.splice(j, 1);
}
if(called.length < 0)
{
return;
} else
{
return number;
}
}
}
if(called.length === 0)
{
index = "No More Numbers";
}else
{
index = rando();
display.push(index);
}
document.getElementById('bingo').innerHTML = index;
}
function show()
{
for(let n = 0; n < display.length; n++)
{
document.getElementById('reveal').innerHTML += "<br/>" + display[n] + "<br/>";
}
}
</script>
</div>
<div id="button">
<button onclick="getRandomNum()">Random Number</button>
</div>
<br/>
<br/>
<br/>
<div id="reveal">
<button onclick="show()">Numbers Called</button>
</div>
</body>
</html>
My only issue is that when it gets to the last element of the original array, it generates "undefined"
instead of a value.
Need help with fixing that part so that it displays "No more numbers"
once all the elements have been randomly generared and removed.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…