How to generate random numbers with no repeat javascript

前端 未结 4 1172
庸人自扰
庸人自扰 2020-12-07 05:14

I am using the following code which generates random number between 0 to Totalfriends, I would like to get the random numbers but they should not be repeated. Any idea how?<

4条回答
  •  心在旅途
    2020-12-07 05:37

    1. create an array (e.g. yourarray) of numbers in range [1..totalfriends]
    2. shuffle the array (e.g. using a javascript implementation of Fisher-Yates algorithm)
    3. inside the for (from 0 to yourarray.length - 1) make a pop() from the array (or just get the n-th element) so you will get everytime a different number

    Doing so you you will avoid to get duplicated numbers

提交回复
热议问题