previous

page 18

next
Shuffle an Array

Sadly, JavaScript doesn't have a built-in function to shuffle an array so I've had to write one. I suggest that you just copy & paste my Shuffle function whenever you need to shuffle an array. I haven't even bothered to color code it!

So give it a go:

<script>
var arr=[12,52,38,26];
Shuffle(arr);
for (var i=0; i<4; i++) {
document.write(arr[i] + ' ');
}

      function Shuffle(array) {
        var i,j,temp;
        for (i=array.length-1; i>0; i-=1) {
          j=Math.floor(Math.random()*(i+1));
          temp=array[i]; array[i]=array[j];
          array[j]=temp;
        }
      }

</script>

Notice that every time you reload your play1.html web page, the order of the numbers changes.

previous
next