How can I make a random array with no repeats?

前端 未结 6 1880
星月不相逢
星月不相逢 2020-12-20 04:13

I\'ve been searching around for some answers to this issue, but nothing seems to work when I try to find a solution.

What I\'m trying to achieve is to make a spinner

6条回答
  •  囚心锁ツ
    2020-12-20 04:21

    It looks like you already have an array of the possible values. In this case you can simply shuffle the array and go through it. JavaScript doesn't have a built in shuffle function, but its pretty simple to implement.

    Here is an example of a Fisher–Yates shuffle

    function shuffle(array) {
      for(var i = array.length; i > 1; i--) {
        var r = Math.floor(Math.random() * i);
        var temp = array[r];
        array[r] = array[i-1];
        array[i-1] = temp;
      }
    }
    

提交回复
热议问题