JavaScript generate random number except some values

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

    You can build an array dynamically. Depending on where you are getting the excluded numbers. Something like:

    var excluded = [8, 15];
    var random = [];
    for(var i = min; i <= max; i++) {
      if(excluded.indexOf(i) !== -1) {
        random.push(i);
      }
    }
    

    Then use the tips found in the answer for this post: How can I generate a random number within a range but exclude some?. Should get you to where you want to go.

提交回复
热议问题