2014-02-27 15 views
1

來自同一陣列中兩個不同的隨機項目,我希望得到來自JS同一陣列中兩個不同的隨機項目。有堆棧溢出相關的問題,但我不明白Fisher Yates Shuffle是如何工作的。我需要搜索整個數組來檢索這些項目,但數組的大小很小。獲取JS

目前,我有一個while循環,但這似乎並沒有被acheiving的最有效的方法:

var honeyPots = ["Fname", "EmailAddress", "Lname", "Telephone", "Address1", "Address2", "Surname", "Title"]; //Fake field names to dupe the bots! 
    var honeyPot = honeyPots[Math.floor(Math.random()*honeyPots.length)]; //Get a random field name from the array 
    var honeyPot2 = honeyPots[Math.floor(Math.random()*honeyPots.length)]; //Get a random field name from the array 
    while (honeyPot == honeyPot2) 
     { 
     var honeyPot2 = honeyPots[Math.floor(Math.random()*honeyPots.length)]; 
     } 

回答

6

只是洗牌數組,並得到前兩個項目:

var honeyPots = ["Fname", "EmailAddress", "Lname", "Telephone", "Address1", "Address2", "Surname", "Title"]; 

var results = honeyPots 
    .sort(function() { return .5 - Math.random() }) // Shuffle array 
    .slice(0, 2); // Get first 2 items 

var honeyPot = results[0]; 
var honeyPot2 = results[1]; 
+0

1爲那種功能 – tewathia

+0

對不起,是迂腐,是那種功能的類似的概念到其中費希爾耶茨隨機定義? – Barney

+0

不,這是另一種方法。 –

0

你可以這樣做,

var arr = [1,2,3,4,4,5,8]; 
var randomValue = []; 
for(i=arr.length; i>=0; i--) { 
    var randomNum = Math.floor(Math.random() * i); 
    randomValue.push(arr[randomNum]); 
    if(i==arr.length-1)break; 
} 
console.log(randomValue); 

希望它有幫助。