How can I make a random array with no repeats?

前端 未结 6 1979
星月不相逢
星月不相逢 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:30

    This function will use Math.random() to randomly choose a number in an array, and not choosing it again until all numbers were used:

    var originalArray = ['360', '330', '300', '270', '240', '210', 
    '180', '150', '120', '90', '60', '30'];
    
    var totalSpin = [];
    
    function spinArray(){
        var spin = Math.floor(Math.random()*originalArray.length);
        if(totalSpin.indexOf(spin) == -1){
            totalSpin.push(spin);
            parag.innerHTML = originalArray[spin];
        } else { 
            spinArray(); 
        }
        if(totalSpin.length == originalArray.length)
              totalSpin = [];
    }
    

    Here is the fiddle: https://jsfiddle.net/628yqz0v/4/

提交回复
热议问题