简体   繁体   中英

Print array in random order?

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

  1. You add 1 to i even after you collide with a value that was already selected, so you will not always print 4 times.
  2. You override the data each time you print using innerHTML = . You need to allow for the old html to stay there, by using append.

My bad. Adjusted:

document.getElementById('test1-drinks').innerHTML = contents[random]+spacing;

to

document.getElementById('test1-drinks').innerHTML += contents[random]+spacing;

so I wouldn't keep replacing the randomized order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM