This chapter introduces how to implement the simple four-bit random number function through code examples.
A relatively simple way to implement it is to randomly extract four non-repetitive characters from numbers and letters.
The code example is as follows:
function only(ele,arr){ if(arr.length==0){ return true; } for(var j=0;j<arr.length;j++){ if(ele==arr[j]){ return false; }else{ return true; } } } var arr=[0,1,2,3,4,5,6,"a","b","c","d","e","f","g"]; (function(){ var randNum=null; var old=[]; var str=""; function done(){ randNum=Math.floor(Math.random()*14); if(only(randNum,old)){ str=str+arr[randNum]; old.push(randNum); } else{ done(); } } for(var index=0;index<4;index++){ done(); } console.log(str); })(arr)The above code implements our requirements. Let’s introduce the implementation process of the above code.
1. Code comments:
1.function only(ele,arr){}, this function can determine whether the specified index has been used and the random number will be repeated.
2.if(arr.length==0){}, if the array is empty, it means that it cannot be a duplicate situation, and returns true.
3.for(var j=0;j<arr.length;j++){}, if the array is not empty, iterates over the elements in the array and compares. If there is no duplication, it returns true, otherwise it returns false. 4.var arr=[0,1,2,3,4,5,6,"a","b","c","d","e","f","g"], obtain an array of random numbers, and of course it can be expanded.
5.(function(){})(arr), a self-executing function and passing a parameter.
6.var randNum=null, declares a variable and assigns the initial value to null, to store the randomly generated array index.
7.var old=[], create an empty array to store the array index value that has appeared.
8.var str="", create an empty string to store the generated random numbers.
9.function done(){}, this function can be used to obtain a random number.
10.randNum=Math.floor(Math.random()*14), get the index value of the array.
11.if(only(randNum,old)){
str=str+arr[randNum];
old.push(randNum);
}, determine whether it has been used. If not, get the array element and append it to the str string, and finally append this index value to the old array.
12.else{ done();
}, If you have used it, then get it again, here is the way to use recursion.
13.for(var index=0;index<4;index++){
done();
}, use a for loop to get 4 random numbers.
From: http://www.softwhy.com/forum.php?mod=viewthread&tid=16493