JavaScript generate random number except some values

后端 未结 13 1638
野性不改
野性不改 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 12:07

    Right now I'm using this and it works without causing browser issues with infinities loops, also tested in mobile devices (using Ionic/Cordova):

    function getRandomIndex(usedIndexs, maxIndex) {
        var result = 0;
        var min = 0;
        var max = maxIndex - 1;
        var index = Math.floor(Math.random()*(max-min+1)+min);
    
        while(usedIndexs.indexOf(index) > -1) {
            if (index < max) {
                index++;
            } else {
              index = 0;
            }
        }
    
        return index;
    }
    

提交回复
热议问题