Reputation: 3
I'm in the middle of a simple app, the idea is to randomly pick up without repeating the values of an array.
I managed to do it through a function but at the moment I started to go through it I got two undefined and I do not know why
Sample of code :
var num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
cont = 0;
totalnum = num.length - 1;
function next() {
var indice = Math.floor(Math.random() * (cont < totalnum ? ++cont : 0));
var number = num[indice];
document.getElementById("hola2").innerHTML = num.splice(indice, 1);
}
Upvotes: 0
Views: 56
Reputation: 171700
Since splice()
changes the length of the array just use length of num
each time to get the random index and you don't need the other variables
var num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function next() {
if (!num.length) return;// do something when no more exist
var indice = Math.floor(Math.random() * num.length);
var number = num.splice(indice, 1);
document.getElementById("hola2").innerHTML = number;
}
document.getElementById("btn").addEventListener('click', next)
<div id="hola2"></div>
<button id="btn">Next</button>
Upvotes: 1
Reputation: 11581
You're setting the value of totalnum
only once at the start and not updating it, even as you are using splice
to remove entries from the array. So after a few calls of next()
you are more and more likely to access indices of the array that are now undefined
because they've been spliced out. You need to update the value of totalnum
as you go or simply refer to the array length directly (I prefer to use the latter as it is simpler, more intuitive, and readable).
<script>
var num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
cont = 0;
function next() {
var indice = Math.floor(Math.random() * (cont < num.length ?++cont:0));
var number = num[indice];
document.getElementById("hola2").innerHTML =num.splice(indice,1);
}
</script>
Upvotes: 1