There is a very convenient function shuffle() in PHP that disrupts arrays. This function is used in many cases, but JavaScript arrays do not have this method. It doesn’t matter. You can expand one, do it yourself, and have enough food and clothing.
Please refresh the page to see the random sorting effect.
Copy the codeThe code is as follows:
<script type="text/javascript">
//<![CDATA[
// Description: Add shuffle method to Javascript array
var shuffle = function(v){
for(var j, x, i = ; i; j = parseInt(() * 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];
("A = ", (","), "<br />shuffle(A) = ", shuffle(a));
//]]>
</script>
Output result:
Copy the codeThe code is 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
() = 0,4,2,8,5,1,3,6,9,7
Add a method to the array via prototype:
Copy the codeThe code is as follows:
<script type="text/javascript">
//<![CDATA[
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
if (!) {
= function() {
for(var j, x, i = ; i; j = parseInt(() * i), x = this[--i], this[i] = this[j], this[j] = x);
return this;
};
}
("A = ", (","), "<br />() = ", ());
//]]>
</script>