I'm trying to output a javascript array of 4 items in a random order. Problem is, I can only get one to print randomly, like this:
Sequence:
Diet Coke
..but I would like it to print something similar to:
Sequence:
Diet Coke
Psuedo Coke
None-psuedo Coke
Coke Zero
..in a random order, of course.
<div id="test1"></div>
<div id="test1-drinks"></div>
<script>
var contents=new Array()
contents[0]='Coke Zero'
contents[1]='Diet Coke'
contents[2]='Psuedo Coke'
contents[3]='None-psuedo Coke'
var i=0
var random
var spacing="<br>"
while (i<contents.length){
random=Math.floor(Math.random()*contents.length)
document.getElementById('test1').innerHTML = "Sequence:<br>";
if (contents[random]!="selected"){
document.getElementById('test1-drinks').innerHTML = contents[random]+spacing;
//mark element as selected
contents[random]="selected"
i++
}
}
</script>
I was hoping the while-loop would cover that for me, but it's not.. Any help is appreciated, and languages php, jQuery and JavaScript are all much welcome.
EDIT: Script's from here, but I don't want document.write to be used to I tried fixing it up.
You could splice the array with a random index until the array is empty.
var contents = ['Coke Zero', 'Diet Coke', 'Psuedo Coke', 'None-psuedo Coke'];
while (contents.length) {
document.write(contents.splice(Math.floor(Math.random() * contents.length), 1) + '<br>');
}
Step 1: Define your array:
var contents=new Array()
contents[0]='Coke Zero'
contents[1]='Diet Coke'
contents[2]='Psuedo Coke'
contents[3]='None-psuedo Coke'
Step 2: Randomly order the array:
contents.sort(function() {
return .5 - Math.random();
});
Step 3: Print the values:
$.each(contents, function(index,value) {
document.getElementById('test1-drinks').append(value + "<br/>");
});
Your problem
i even after you collide with a value that was already selected, so you will not always print 4 times.innerHTML =. You need to allow for the old html to stay there, by using append.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With