Javascript generate random unique number every time

后端 未结 7 1315
予麋鹿
予麋鹿 2021-01-15 16:25

Ok so i need to create four randomly generated numbers between 1-10 and they cannot be the same. so my thought is to add each number to an array but how can I check to see i

7条回答
  •  清酒与你
    2021-01-15 16:39

    Here is a recursive function what are you looking for.

    "howMany" parameter is count of how many unique numbers you want to generate.
    "randomize" parameter is biggest number that function can generate.
    

    for example : rand(4,8) function returns an array that has 4 number in it, and the numbers are between 0 and 7 ( because as you know, Math.random() function generates numbers starting from zero to [given number - 1])

    var array = [];
    var isMatch= false;
    function rand(howMany, randomize){
         if( array.length < howMany){
        var r = Math.floor( Math.random() * randomize );
        for( var i = 0; i < howMany; i++ ){
            if( array[i] !== r ){
               isMatch= false;
               continue;
                } else {
               isMatch= true;
               break;
            }
        }
        if( isMatch == false ){
           array.push(r);
               ran(howMany, randomize);
        }
            ran(howMany, randomize);
        return array;
         }
    }
    

提交回复
热议问题