Javascript generate random unique number every time

后端 未结 7 1317
予麋鹿
予麋鹿 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:52
    var a = [];
    for (var i = 0; i < 5; i++) {
      var r = Math.floor(Math.random()*10) + 1;
      if(!(r in a))
        a.push(r);
      else
        i--;
    }
    

    That'll do it for you. But be careful. If you make the number of random numbers generated greater than the may number (10) you'll hit an infinite loop.

    0 讨论(0)
提交回复
热议问题