Javascript generate random unique number every time

后端 未结 7 1370
予麋鹿
予麋鹿 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:40

    I'm using a recursive function. The test function pick 6 unique value between 1 and 9.

    //test(1, 9, 6);
    
    function test(min, max, nbValue){
        var result = recursValue(min, max, nbValue, []);
        alert(result);
    }
    
    function recursValue(min, max, nbValue, result){
        var randomNum = Math.random() * (max-min);
        randomNum = Math.round(randomNum) + min;
    
        if(!in_array(randomNum, result)){
            result.push(randomNum);
            nbValue--;
        }
    
        if(nbValue>0){
            recursValue(min, max, nbValue, result);
        }
        return result;
    }
    
    function in_array(value, my_array){
        for(var i=0;i< my_array.length; i++){
            if(my_array[i] == value){
                console.log(my_array+" val "+value);
                return true;   
            }        
        }
        return false;
    }
    

提交回复
热议问题