如何在javascript中随机生成数字而不重复?

Sho*_*vik 6 javascript arrays random for-loop

我想使用javascript随机生成0到4之间的每个数字,每个数字只能出现一次.所以我写了代码:

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

但是这段代码重复了这些值.请帮忙.

Ble*_*der 17

生成一系列数字:

var numbers = [1, 2, 3, 4];
Run Code Online (Sandbox Code Playgroud)

然后洗牌:

function shuffle(o) {
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

var random = shuffle(numbers);
Run Code Online (Sandbox Code Playgroud)


dfs*_*fsq 7

还有一种方法:

for (var a = [0, 1, 2, 3, 4], i = a.length; i--; ) {
    var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
    console.log(random);
}
Run Code Online (Sandbox Code Playgroud)

不知道是否有可能使它更紧凑.

测试:http://jsfiddle.net/2m3mS/1/

这是嵌入演示:

$('button').click(function() {
    $('.output').empty();
    
    for (var a = [0, 1, 2, 3, 4], i = a.length; i--; ) {
        var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
        $('.output').append('<span>' + random + '</span>');
    }
    
}).click();
Run Code Online (Sandbox Code Playgroud)
.output span {
    display: inline-block;
    background: #DDD;
    padding: 5px;
    margin: 5px;
    width: 20px;
    height: 20px;
    text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"></div>
<button>Run</button>
Run Code Online (Sandbox Code Playgroud)


Ing*_*ürk 5

Adil和Minko给出的答案存在一个主要问题(尽管Minko至少将其限制在一小组数字中):他们一遍又一遍地重复相同的数字.

从这个意义上讲,一个更好的方法是创建包含可能值的数组,对其进行随机播放,然后只是弹出元素.这将需要改组阵列的复杂性,但它将摆脱上面提到的问题.

var elements = [1, 2, 3, 4];
elements.shuffle(); // not a standard Javascript function, needs to be implemented

while( elements.length > 0 ) {
    console.log( elements.pop() );
}
Run Code Online (Sandbox Code Playgroud)