1: Randomly generate a set of numbers and insert them into the array:
function Randomarray (len, Min, max) { if (len > (max-min + 1)) {throw new Error (' Len > (max-min + 1) ')}//Check the Set Whether the set exceeds the predetermined total, and if so, throws an exception var result = []; for (var i = 0; i < len; i++) { var e = Math.floor (Math.random () * (Max-min + 1) + min); Result.push (e); } return result;} Console.dir (Randomarray (6, 2, 7));
2: The first step has randomly generated a set of arrays, but the number inside the array may be duplicated, so if you want to do not repeat the array of numbers, you have to implement the array to repeat the item:
function check (result, e) {for (i = 0; i < result.length; i++) { if (result[i] = = e) {//traversal array to see if the number in the array is the E phase being generated If yes, return true; return true;} } return false;}
3: There is already a way to check if there are duplicates in the array, but to call the check function before Result.puse (e), the complete code is as follows:
function Randomarray (len, Min, max) { if (len > (max-min + 1)) {throw new Error (' Len > (max-min + 1) ')}//Check the Set Whether the set exceeds the predetermined total, and if so, throws an exception var result = []; for (var i = 0; i < len; i++) { do{ var e = Math.floor (Math.random () * (Max-min + 1) + min), } while (check ( result, E)); Result.push (e); } return result;} function check (result, e) {for (i = 0; i < result.length; i++) { if (result[i] = = e) {//traversal array to see if the numbers inside the array are The generated e is the same, and if it is, returns true; return true;} } return false;} Console.dir (Randomarray (6, 2, 7));
There are other array de-weight methods that use the recorded records as a backup:
1: With hasOwnProperty.
hasOwnProperty: is used to determine whether an object has a property or object that you give a name to. However, it is important to note that this method cannot check whether the object has this property in its prototype chain, and that the property must be a member of the object itself.
function check (result, e) {for (var i = 0; i < result.length; i++) { if (Result.hasownproperty (e)) { Retu RN true; } } return false;}
Randomly generate an array, and go to duplicate items