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.
The code copy is 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 result:
The code copy 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
A.shuffle() = 0,4,2,8,5,1,3,6,9,7
Add a method to the array via prototype:
The code copy is 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>