The inscheduled array means to disrupt the order of all elements in the array.
A common method is to pass a function to the native sort method of the array, which randomly returns 1 or -1 to achieve the purpose of randomly arranging array elements.
The code copy is as follows:
arr.sort(function(a,b){ return Math.random()>.5 ? -1 : 1;});
Although this method is intuitive, it is not efficient. After my test, it messed up an array of 10,000 elements, and the time it took was about 35ms (firefox)
I have always had the excellent quality of breaking the casserole to ask the end, so I found an efficient method. See this original text
The code copy is 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 adds a function to Array.prototype, called shuffle - but the name does not matter, what is important is its efficiency.
Take the array of 10,000 elements above to test it. It only takes 7 or 8 milliseconds to complete it in out-of-order using this method.
Increase array elements by 10 times to 100,000 for testing. The first sort method takes about 500+ms, and the shuffle method takes about 40ms. The difference is huge.
Complete test code:
The code copy is 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, have you noticed the for loop in the shuffle code? It doesn’t have the second half! That is, there is only for(..) but not the following {..}, so you can write this way! And it actually executed normally! It's so curious, I have to go to the blog park to ask.