JavaScript generate random number except some values

后端 未结 13 1642
野性不改
野性不改 2021-01-05 11:26

I\'m generating random numbers from 1 to 20 by calling generateRandom(). How can I exclude some values, say 8 and 15?

function generateRandom(mi         


        
13条回答
  •  抹茶落季
    2021-01-05 11:54

    You can simply do like this

    function generatedRandExclude(showed,max) {
         let randNo = -1;
         while(showed.length < max) {
            	randNo = Math.floor(Math.random() * Math.floor(max));	
             	if(!showed.includes(randNo)) {
                	showed.push(randNo);
                 	break;
              }
         }
         return randNo;
    }
    
    let showed = [];
    function run() {
        console.log(generatedRandExclude(showed,6));
    }
    run();
    run();
    run();
    run();

    generatedRandExclude generate random number excluded using array showed.

提交回复
热议问题