I want to generate a number from 0 to 10 randomly using JavaScript and each number can appear only once. Is there a possibility
            Asked
            
        
        
            Active
            
        
            Viewed 1,119 times
        
    -2
            
            
        - 
                    What've you tried yourself? – Andrew Li Dec 13 '16 at 12:56
- 
                    When you say you want to generate *a* random number which can only appear once, do you mean to want to generate several? And stop on a repeat? Or have the numbers 0..10 in a random permuation? Or something else? – doctorlove Dec 13 '16 at 12:57
- 
                    2Actually numbers in row from 0 to 10 **is** random and does not repeats. – Justinas Dec 13 '16 at 12:58
- 
                    Possible duplicate of [How to randomize (shuffle) a JavaScript array?](http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – Bathsheba Dec 13 '16 at 12:59
2 Answers
0
            
            
        This can be a solution :
HTML :
<button onclick="getNumber()">click</button>
JS :
var number = [0,1,2,3,4,5,6,7,8,9,10];
function getNumber() {
    if (0 === number.length) {
        alert('Finish')
    } else {
        var index = Math.floor(Math.random() * number.length);
        alert(number[index]);
        number.splice(index, 1);
    }
}
 
    
    
        jean-max
        
- 1,640
- 1
- 18
- 33
- 
                    Thanks for the help, perhaps badly expressed but I want to get the effect of generating a random number between 1 and 10 and not to duplicate to display all ten numbers. – samuraijack Dec 14 '16 at 07:11
- 
                    Don't understand, you only want that the script generate a number between 1 and 10. That's all ? – jean-max Dec 14 '16 at 08:08
0
            
            
        let arr = []
// 6 is max length of num taken, change it to your convenience
while (arr.length < 6) {
    Random = Math.floor(Math.random() * 6);
    // console.log(Random);
    
    let indexValue = arr.indexOf(Random);
    console.log(Random, indexValue);
    if (indexValue == -1) {
        arr.push(Random);
    }
}
console.log(arr);
// the code will push numbers between 0 to 5 without repetition
// into an empty array 
    
    
        Bandantonio
        
- 816
- 1
- 7
- 19
 
    
    
        shacz007
        
- 1
- 1
