How do you randomly generate X amount of numbers, between the range of Y and Z in JavaScript?

前端 未结 3 1833
情歌与酒
情歌与酒 2021-01-22 17:08

For example I would like to generate 5 unique numbers between 1 & 10. The results should be 5 numbers from 1 to 10(for example 2 3 4 8 10).

3条回答
  •  不要未来只要你来
    2021-01-22 17:58

    Another method is to produce random numbers and only add them to the returning array if it does not already include them.

    function randomRange(from, to, leng){
        var tem, A= [], L= 0, i= 0;
        randomRangeLoop: 
        while(L< leng){
            tem= Math.floor(Math.random()*to)+from;
            i= 0;
            while(i

    alert(randomRange(1, 10, 5))

    /* returned value: (Array) 8,6,1,3,5 */

提交回复
热议问题