PHP has a very convenient to disrupt the array of functions shuffle (), this function in many cases will be used, but the JavaScript array does not have this method, it does not matter, you can expand A, do-it-yourself, well-clothed.
Please refresh the page to see the random sort effect.
Copy Code code as follows:
<script type= "Text/javascript" >
<! [cdata[
Description: Add Shuffle method to 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:
Copy Code code as follows:
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 by prototype:
Copy Code code as follows:
<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>