JS, to disrupt the array there are many ways, online spread a foreign people write method, I think is the most concise:
function Randomsort (A, b) {
Return Math.random () >.5? -1:1;//uses the Math.random () function to generate random numbers between 0~1 and 0.5, and returns-1 or 1
}
var arr = [1, 2, 3, 4, 5];
Arr.sort (Randomsort);
Here's a description of the next sort () function, in which a function is built into the array object in JS:
Arrayobj.sort ([sortfunction])
This method sorts the array object appropriately, and does not create a new array object during execution.
Sortfunction is optional.
is the name of the function used to determine the order of elements. If this argument is omitted, then the elements are sorted in ascending order in ASCII characters.
The Sortfunction method has two parameters. Represents each of the two array entries for each sort comparison. Sort () performs this argument each time the comparison of two array entries is performed and passes the two comparison array items as arguments to the function. The order of two array items is exchanged when the function returns a value of 1, otherwise it is not exchanged.
We can make a slight change to the above Randomsort () to achieve ascending and descending order:
Return a < b? -1:1;//If the a<b is not exchanged, the exchange, that is, ascending order
}
Return a > B? -1:1;;/ /If the a>b does not exchange, otherwise exchange, will arrange the order
}
Alternatively, a nameless function can be directly placed in a call to the sort () method. The example below is an odd number in front and an even number in the following example:
The following is a reference fragment:
Document.writeln (ARRA); Output: 1,5,3,4,6,2