I think it is the most concise way to spread a foreign-written method on the Internet:
Program code
Using the Math.random () function to generate a random number between 0~1 and 0.5, return-1 or 1
The code is as follows |
Copy Code |
function Randomsort (A, b) { Return Math.random () >.5? -1:1; } var arr = [1, 2, 3, 4, 5]; var arr2 = Arr.sort (Randomsort); alert (ARR2); |
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.
Here are some friends from the country wrote
The code is as follows |
Copy Code |
Gets the random number in an array Hf. Math.randomnumbers is a prefix that can be defined by itself, mainly looking at logical code Hf. Math.randomnumbers = function (Startnum, Endnum, Count, repeat) { var ret = []; if (repeat) { for (var i = 0; i < count; i++) { Ret[i] = HF. Math.random (Startnum, endnum); } return ret; } var tmp = []; var i = 0; for (var s = startnum s <= endnum; s++) { tmp[i++] = s; } var L = tmp.length; for (i = 0; i < count; i++) { Ret[i] = HF. Array.remove (TMP, HF. Math.random (0,--l)); } return ret; } |
Some examples of generating random arrays
The code is as follows |
Copy Code |
To define an array that holds the generated random numbers var array=new array ();
Cyclic n-Generation random number for (var i = 0;; i++) { Generates only 10 random numbers if (array.length<10) { Generaterandom (10); }else{ Break } }
Iterate through the array of random numbers for (var i = 0; i < Array.Length; i++) { Alert (Array[i]); }
Methods of generating random numbers function Generaterandom (count) { var rand = parseint (Math.random () *count); for (var i = 0; i < Array.Length; i++) { if (array[i] = = Rand) { return false; } } Array.push (RAND); } |