JavaScript implementation of PHP shuffling array function shuffle instance

  • 2020-03-30 04:05:14
  • OfStack

PHP has a handy function called shuffle() to shuffle an array, which is used in many situations, but javascript arrays don't have this method, so it doesn't matter if you don't have one.

Please refresh the page to see the effect of random sort.


<script type="text/javascript">
//<![CDATA[
//Add the shuffle method
to the Javascript array  
var shuffle = function(v){
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
};
 
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
 
document.write("A = ", a.join(","), "<br />shuffle(A) = ", shuffle(a));
 
//]]>
</script>

Output results:


A = 0,1,2,3,4,5,6,7,8,9 shuffle(A) = 1,5,0,9,2,3,6,8,4,7
A.shuffle() = 0,4,2,8,5,1,3,6,9,7

Add a method to the array through prototype:


<script type="text/javascript">
//<![CDATA[
 
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
 
if (!Array.prototype.shuffle) {
    Array.prototype.shuffle = function() {
        for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
        return this;
    };
}
 
document.write("A = ", a.join(","), "<br />A.shuffle() = ", a.shuffle());
 
//]]>
</script>


Related articles: