Quick fix:
var numero = Math.floor(Math.random()*8);
return numero>4 ? numero+1 : numero
Explanation:
There are many ways to do it, but I’ll make a very simple one for your case.
First, let’s understand the problem. You want one of eight possibilities, but the output is not sequential:
0 1 2 3 4 5 6 7 <-- posição sequencial dos números (aqui é feito o random)
0 1 2 3 4 6 7 8 <-- saída desejada (simplesmente modificamos o retorno com if)
So you want some of these eight numbers. In other words,:
var numero = Math.floor(Math.random()*8);
It’s two sequences, zero to four, and six to eight, so just add one if it’s bigger than four:
return numero>4 ? numero+1 : numero
If give 0 1 2 3 4 returns 0 1 2 3 4 respectively...
... and, if der 5 6 7 returns 6 7 8 respectively
Thus remaining the code:
var numero = Math.floor(Math.random()*8);
return numero>4 ? numero+1 : numero
If you do not know the conditional operator (called ternary) is the same as doing this:
var numero = Math.floor(Math.random()*8);
if (numero>4) {
return numero + 1;
} else {
return numero;
}
Test here:
function randomDeZeroAOitoMenosOCinco() {
var numero = Math.floor(Math.random()*8);
return numero>4 ? numero + 1 :numero;
}
document.getElementById('sortear').onclick = function() {
document.getElementById('resultado').innerText = randomDeZeroAOitoMenosOCinco();
};
<button id="sortear">Clique-me!</button>
<span id="resultado">?</span>
And if it were a more complex sequence?
Whenever you think of various things (playing cards, non-sequential numbers, names) think of them as "items" and not sequentially (even if they are numbers, you can "number each one in sequence"). Then you draw his index, and then you take the value:
var possibilidades = [ 0, 1, 2, 3, 4, 6, 7, 8 ];
return possibilidades[Math.random()*possibilidades.length];
Noticed that in this case you can put on array the sequence you want?
Test here:
function randomCustomizado() {
var possibilidades = [ 0, 1, 2, 3, 4, 6, 7, 8 ];
return possibilidades[Math.floor(Math.random()*possibilidades.length)];
}
document.getElementById('sortear').onclick = function() {
document.getElementById('resultado').innerText = randomCustomizado();
};
<button id="sortear">Clique-me!</button>
<span id="resultado">?</span>
Excellent. In my case of the question, this part of the code is inside a switch case, because I’m creating a memory game to learn Javascript (I’m a beginner). With just a few modifications of your solution placing within a recursive function, it worked here.
– Igor
@Igorpedra added a more interesting function at the end, which serves for any sequence (and even for strings).;
– Bacco
If you remember this, it will help a lot when you need "Random" of various items: Do not add the items (in your case it would be like taking the values you want and number from zero to eight, and the fifth value is six, and so on), it facilitates the reasoning.
– Bacco