This example summarizes the method of randomly disrupting arrays by JS. Share it for your reference, as follows:
In JS, there are many ways to disrupt arrays. I think the method written by a foreigner is the most concise:
function randomsort(a, b) { return Math.random()>.5 ? -1 : 1; //Use the Math.random() function to generate a random number between 0~1 and compare it with 0.5, and return -1 or 1}var arr = [1, 2, 3, 4, 5];arr.sort(randomsort);Here is the sort() function. A function is built into the Array object in JS:
arrayobj.sort([sortfunction])
This method sorts the Array objects appropriately; no new Array objects are created during execution.
sortFunction is optional.
is the name of the function used to determine the order of elements. If this parameter is omitted, the elements will be arranged in ascending order in ASCII character order.
The sortFunction method has two parameters. Represents two array items each time the sort comparison is respectively. When sort() sorting, this parameter is executed again every time two array items are compared, and the two compared array items are passed to this function as parameters. When the function returns a value of 1, the order of the two array items is exchanged, otherwise it will not be exchanged.
We can make a slight modification to the above randomsort() to achieve ascending and descending order:
function asc(a,b) {return a < b ? -1 : 1;//If a<b does not exchange, otherwise exchange, that is, ascending order}function desc(a,b) {return a > b ? -1 : 1;//If a>b does not exchange, otherwise exchange, that is, ascending order}In addition, you can directly put an unnamed function into the call of the sort() method. The following example is to rank odd numbers in front and even numbers in back. The example is as follows:
The following is a quoted snippet:
var arrA = [6,2,4,3,5,1];arrA.sort( function(x, y) {if (x % 2 ==0) return 1;if (x % 2 !=0) return -1;});document.writeln(arrA); //Output: 1,5,3,4,6,2For more information about JavaScript related content, please check out the topics of this site: "Summary of JavaScript array operation skills", "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm skills", "Summary of JavaScript animation special effects and techniques", "Summary of JavaScript errors and debugging skills", "Summary of JavaScript data structures and algorithm skills", "Summary of JavaScript traversal algorithms and techniques" and "Summary of JavaScript mathematical operation usage"
I hope this article will be helpful to everyone's JavaScript programming.