How to randomly generate numbers without repetitio

2019-01-26 13:30发布

I want to generate each number between 0 to 4 randomly using javascript and each number can appear only once. So I wrote the code:

for(var l=0; l<5; l++) {
    var randomNumber = Math.floor(Math.random()*5);  
    alert(randomNumber)
}

but this code is repeating the values. Please help.

7条回答
▲ chillily
2楼-- · 2019-01-26 14:21

If the range of random numbers is not very large you can use this:

var exists = [],
    randomNumber,
    max = 5;
for(var l = 0; l < max; l++) {
   do {
       randomNumber = Math.floor(Math.random() * max);  
   } while (exists[randomNumber]);
   exists[randomNumber] = true;
   alert(randomNumber)
}

DEMO

查看更多
登录 后发表回答