An array of sequences means that all elements in an array are sorted in a disorderly order.
A common approach is to pass a function to the primitive sort method of the array, which randomly returns 1 or 1 to achieve the objective of randomly arranging array elements.
Copy Code code as follows:
Arr.sort (function (a,b) {return math.random () >.5 -1:1;});
This method is intuitive, but not high efficiency, I tested, disrupting the 10,000 elements of the array, the time spent around 35ms (Firefox)
I have always had the good quality of ask why, so I searched for an efficient method. See this in the text
Copy Code code as follows:
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;
};
}
Arr.shuffle ();
This method is to add a function for Array.prototype, called shuffle--but it doesn't matter what the name is, it's his efficiency that matters.
With the array of the 10,000 elements I have above, it takes only 7, 8 milliseconds to complete the sequence in this way.
Add the array element 10 times times to the 100000来 test, the first sort method is time-consuming and 500+ms, the shuffle method takes about 40ms, and the difference is significant.
Complete test Code:
Copy Code code as follows:
var count = 100000,arr = [];
for (Var i=0;i.5 -1:1;});
Array.prototype.sort.call (Arr,function (a,b) {return math.random () >.5 -1:1;});
document.write (arr+ '
');
var T1 = new Date (). GetTime ();
document.write (T1-T);
The following methods are most efficient
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;
};
}
var t = new Date (). GetTime ();
Arr.shuffle ();
document.write ('
' +arr+ '
');
var T1 = new Date (). GetTime ();
document.write (T1-T);
In addition, we have not noticed the shuffle code in the For loop, he did not back half! Which is only for (..) But there is no later {...}, incredibly can write! And actually do it properly! So strange, I have to go to the blog Park to ask.