Random number generator without dupes in Javascript?

后端 未结 6 1786
一生所求
一生所求 2020-11-28 14:53

I need help with writing some code that will create a random number from an array of 12 numbers and print it 9 times without dupes. This has been tough for me to accomplish.

6条回答
  •  死守一世寂寞
    2020-11-28 15:37

    var nums = [1,2,3,4,5,6,7,8,9,10,11,12];
    var gen_nums = [];
    
    function in_array(array, el) {
       for(var i = 0 ; i < array.length; i++) 
           if(array[i] == el) return true;
       return false;
    }
    
    function get_rand(array) {
        var rand = array[Math.floor(Math.random()*array.length)];
        if(!in_array(gen_nums, rand)) {
           gen_nums.push(rand); 
           return rand;
        }
        return get_rand(array);
    }
    
    for(var i = 0; i < 9; i++) {
        document.write(get_rand(nums));
    }
    

提交回复
热议问题