2010-09-15 86 views
19

我需要從JSON結果實現隨機化。JavaScript - 在對象內部混洗對象(隨機化)

的JSON格式是兩個對象:

結果:

問題(目的)

[Object { id="4c6e9a41470b19_96235904", more...}, 
Object { id="4c784e6e928868_58699409", more...}, 
Object { id="4c6ecd074662c5_02703822", more...}, 6 more...] 

主題(對象)

[Object { id="3jhf3533279827_23424234", more...}, 
Object { id="4634663466cvv5_43235236", more...}, 
Object { id="47hf3892735298_08476548", more...}, 2 more...] 

我想要t o隨機化問題對象和主題對象內的對象的順序。

+1

那些不是對象,那些是包含對象的**數組**。 – 2014-11-19 09:52:32

回答

26

你可以使用一個Fisher-Yates-Durstenfeld shuffle

var shuffledQuestionArray = shuffle(yourQuestionArray); 
var shuffledTopicArray = shuffle(yourTopicArray); 

// ... 

function shuffle(sourceArray) { 
    for (var i = 0; i < sourceArray.length - 1; i++) { 
     var j = i + Math.floor(Math.random() * (sourceArray.length - i)); 

     var temp = sourceArray[j]; 
     sourceArray[j] = sourceArray[i]; 
     sourceArray[i] = temp; 
    } 
    return sourceArray; 
} 
6

我發現this post關於使用Fisher-Yates algorithm在JavaScript中對數組進行混洗。它使用此功能:

function fisherYates (myArray) { 
    var i = myArray.length; 
    if (i == 0) return false; 
    while (--i) { 
    var j = Math.floor(Math.random() * (i + 1)); 
    var tempi = myArray[i]; 
    var tempj = myArray[j]; 
    myArray[i] = tempj; 
    myArray[j] = tempi; 
    } 
} 
+5

你不必讓'tempj' – pepkin88 2010-09-15 15:16:53

+0

就像冠軍! – 2014-01-14 09:54:52

7

最簡單的方法(不完美的洗牌,但在某些情況下可能會更好):

function randomize(a, b) { 
    return Math.random() - 0.5; 
} 

yourQuestionArray.sort(randomize); 
yourTopicArray.sort(randomize); 

yourQuestionArray.sort(function (a, b) {return Math.random() - 0.5;}); 
yourTopicArray.sort(function (a, b) {return Math.random() - 0.5;}); 

http://jsfiddle.net/dJVHs/

+2

對於較大的陣列,它可能(可能)會比Fisher-Yates shuffle慢。洗牌將是O(n),而使用排序將(可能)爲O(n log n)。 – LukeH 2010-09-15 17:22:39

+2

@LukeH好吧,你是對的。但這更美麗:P – pepkin88 2010-09-15 20:02:07