If there is an array that looks like this:
var arr1 = ["A", "B", "C", "D"];
How to randomly disrupt the array order, that is, shuffle.
There is a relatively wide spread of simple random algorithms:
function Randomsort (a,b) {return (0.5-math.random ());}
It turns out that the above is not completely random.
A random search on the internet too much of this stuff, look at the StackOverflow on a high score answer, the answer comes from GitHub.
Knuth-shuffle
The Fisher-yates (aka Knuth) shuffle for Browser and Node.js
Let's take a look at the algorithm described above, the code is as follows:
/*jshint-w054 * *
(function (exports) {
' use strict ';
Http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
Function Shuffle ( Array) {
var currentindex = Array.Length
, Temporaryvalue
, Randomindex
;
While there remain elements to shuffle
... while (0!== currentindex) {
//Pick A remaining element ...
Randomindex = Math.floor (Math.random () * currentindex);
Currentindex-= 1;
and swap it with the current element.
Temporaryvalue = Array[currentindex];
Array[currentindex] = Array[randomindex];
Array[randomindex] = Temporaryvalue;
}
return array;
}
Exports.knuthshuffle = shuffle;
} (' undefined '!== typeof exports && exports | | ' Undefined '!== typeof window && Window | | Global));
Authors recommend using a browser:
(function () {
' use strict ';
var a = [2,11,37,42]
, b
;
The shuffle modifies the original array
//calling A.slice (0) creates a copy, which is assigned to B
= window . Knuthshuffle (A.slice (0));
Console.log (b);
} ());
Nodejs:
NPM install-s knuth-shuffle
(function () {
' use strict ';
var shuffle = require (' Knuth-shuffle '). Knuthshuffle
, a = [2,11,37,42]
, b
;
The shuffle modifies the original array
//calling A.slice (0) creates a copy, which is assigned to B
= Shuf Fle (A.slice (0));
Console.log (b);
} ());
There are other variants from this algorithm, such as the For loop below. The rest will not be spoken.
/**
* Randomize array element order In-place.
* Using Durstenfeld shuffle algorithm.
*/
function Shufflearray (array) {for
(var i = array.length-1 i > 0; i--) {
var j = Math.floor (Math.rand Om () * (i + 1));
var temp = array[i];
Array[i] = array[j];
ARRAY[J] = temp;
}
return array;
}
Using ES2015 (ES6)
Array.prototype.shuffle = function () {let
m = this.length, I;
while (m) {
i = (math.random () * m--) >>> 0;
[This[m], this[i]] = [this[i], this[m]]
} return this
;
}
Use:
[1, 2, 3, 4, 5, 6, 7].shuffle ();
Find a lot of Chinese search random algorithm, but is not completely random, efficiency and compatibility are to be refined, suggest that if there is a need to use random scrambling array elements, you can use the above.