This chapter introduces how to implement a simple four-digit random number function through code examples.
A relatively simple way to achieve this is to randomly select four non-repeating 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 meets 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 place random numbers to avoid duplication.
2.if(arr.length==0){}, if the array is empty, it means there is no possibility of duplication and returns true.
3.for(var j=0;j
6.var randNum=null, declare a variable and assign the initial value to null, used to store randomly generated array index.
7.var old=[], creates an empty array to store array index values that have already appeared.
8.var str="", creates an empty string to store the generated random number.
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, obtain the array element and append it to the str string, and finally append this index value to the old array.
12.else{ done();
}, if it has been used, then get it again, using recursion here.
13.for(var index=0;index<4;index ){
done();
}, use a for loop to obtain 4 random numbers.
From: http://www.softwhy.com/forum.php?mod=viewthread&tid=16493