In js, there is no such thing as php that can be used directly to sort data randomly. Here we will write a custom random array sorting function.
There are many ways to randomly arrange javascript arrays. The following is a simple method:
The Code is as follows: |
Copy code |
Function randomSort (a, B ){ Return Math. random ()>. 5? -1:1; } |
If the random number is greater than 0.5,-1 is returned, that is, a is before B. If the random number is less than 0.5, 1 is returned, that is, B is before.
A company's interview question: Randomly disconnects 1-numbers and places them in the JS array. Then, write a function: specify the number of 1-numbers, quickly finds the subscript index number corresponding to this number from the array.
The Code is as follows: |
Copy code |
Var writable r = []; For (var I = 0; I <100; I ++ ){ Pull R. push (I); // pull R [I] = I; } Function randomSort (a, B) {// random arrangement of array elements Return Math. random ()>. 5? -1:1; } Using R. sort (randomSort );
Function showIndex (num ){ For (var j = 0; j <partition R. length; j ++ ){ If (distinct R [j] = num ){ Console. log (j); // output to the console Break; } } } ShowIndex (43 ); |
There are many ways to disrupt Arrays
The Code is as follows: |
Copy code |
Function randomsort (a, B ){ Return Math. random ()>. 5? -1: 1; // Use the Math. random () function to generate 0 ~ The random number between 1 and 0.5 is compared, and-1 or 1 is returned. } Var arr = [1, 2, 3, 4, 5]; Var arr2 = arr. sort (randomsort ); Alert (arr2 ); Arrayobj. sort ([sortfunction])
|
This method sorts Array objects appropriately. During execution, no new Array objects are created.