I constructed a simple switch/case statement that works well. With the press of the enter key, each case is randomly drawn and removed from the array until nothing remains.
However, when I click a button to call a function which contains the same switch/case statement, the code doesn't work the same. Rather than reaching the end of the array, each press of the enter key continually draws a random case without ever ending.
It appears that my array is resetting with every key press. How come the code doesn't function the same when within a function?
var casesDrawn = [0, 1, 2];
document.body.addEventListener( 'keyup', function (e) {
if ( e.keyCode == 13 && casesDrawn.length > 0) {
randSelect();
}
function randSelect(){
var randNum = Math.floor(Math.random() * casesDrawn.length);
var num = casesDrawn[randNum];
casesDrawn.splice(randNum, 1);
switch (num){
case 0:
document.getElementById('show').innerHTML = 'case 0 selected';
break;
case 1:
document.getElementById('show').innerHTML = 'case 1 selected';
break;
case 2:
document.getElementById('show').innerHTML = 'case 2 selected';
break;
}
}
});
function myFunction(){
var casesDrawn = [0, 1, 2];
document.body.addEventListener( 'keyup', function (e) {
if ( e.keyCode == 13 && casesDrawn.length > 0) {
randSelect();
}
function randSelect(){
var randNum = Math.floor(Math.random() * casesDrawn.length);
var num = casesDrawn[randNum];
casesDrawn.splice(randNum, 1);
switch (num){
case 0:
document.getElementById('show').innerHTML = 'case 3 selected';
break;
case 1:
document.getElementById('show').innerHTML = 'case 4 selected';
break;
case 2:
document.getElementById('show').innerHTML = 'case 5 selected';
break;
}
}
});
}
<p id="show"></p>
<button onclick="myFunction()">Click to jump to Function</button>