2016-08-30 20 views
-2

我正嘗試創建一個數組數組。數組應如下所示:數組的隨機數,但不相同| JavaScript

[1, 2, 1][2, 1, 2]

我它已經被選定後,不要再相同數量的希望。

所以我不想[1, 1, 2][2, 2, 1]

我有以下代碼:

var chosenHosts = []; 

for (var i = 0; i < match.match_games; ++i) { 
    var num = 1 + Math.floor(Math.random() * 2); 

    chosenHosts.push(num); 
} 

console.log(chosenHosts); 

此代碼推了相同的號碼。有沒有人有如何實現上述的想法?

P.S.對於令人困惑的標題感到抱歉,我不知道如何描述它。

+0

代碼中沒有jquery – depperm

+0

@depperm是的,對不起。我的意思是,使用JQuery也很好 – Chris

回答

4

像這樣的事情會工作

var chosenHosts = [1 + Math.floor(Math.random() * 2)]; 

for (var i = 1; i < match.match_games; i++) { 
    var num = chosenHosts[i - 1] == 1 ? 2 : 1; 
    chosenHosts.push(num); 
} 

console.log(chosenHosts); 
+0

這將只適用於如果隨機數字在1或2之間 – depperm

+0

真的 - 像OP要求@depperm – baao

+0

@baao這幾乎是我需要的!這輸出4個數字。我只需要3.你有什麼想法如何實現這一目標? – Chris

0

您可以在陣列中檢查的最後一個元素,並繼續創建一個隨機數,直到它的不同。

var chosenHosts = [1 + Math.floor(Math.random() * 2)]; 

for (var i = 0; i < match.match_games; i++) { 
    var r = 1 + Math.floor(Math.random() * 2); 
    while (chosenHosts[i] == r) 
    r = 1 + Math.floor(Math.random() * 2); 
    chosenHosts.push(r); 
} 

console.log(chosenHosts);