This question already has an answer here:
Guys I have array with five strings inside. Then I have loop and inside loop I have Math.random to get 1,2,3,4 and 5 numbers. So as you guess I want to change array's each string randomly, but if I changed one of them once I want to re-random a number and change the next string. The problem is that only re-randoms once but I want it to do until it gets to unchanged string.
<button id="button" onclick="change()">me</button>
<p id="par"></p>
var holder = ["empty","empty","empty","empty","empty"];
var change = function(){
for(var i=0; i<holder.length; i++){
var rand = Math.floor((Math.random() * 5) + 1);
switch (rand) {
case 1:
if (holder[0] === "empty"){
holder[0] = "ocupied"
}else{rand = Math.floor((Math.random() * 5) + 1)}
break;
case 2:
if (holder[1] === "empty"){
holder[1] = "ocupied"
}else{rand = Math.floor((Math.random() * 5) + 1)}
break;
case 3:
if (holder[2] === "empty"){
holder[2] = "ocupied"
}else{rand = Math.floor((Math.random() * 5) + 1)}
break;
case 4:
if (holder[3] === "empty"){
holder[3] = "ocupied"
}else{rand = Math.floor((Math.random() * 5) + 1)}
break;
case 5:
if (holder[4] === "empty"){
holder[4] = "ocupied"
}else{rand = Math.floor((Math.random() * 5) + 1)}
break;
}
document.getElementById('par').innerHTML = holder;
};
Aucun commentaire:
Enregistrer un commentaire