22

我需要从 JSON 结果中实现随机化。

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...]

我想随机化问题对象和主题对象中对象的顺序。

4

3 回答 3

35

您可以使用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;
}
于 2010-09-15T14:12:41.737 回答
12

最简单的方法(不是完美的随机播放,但在某些情况下可能会更好):

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/ )

于 2010-09-15T15:10:19.087 回答
7

我发现这篇关于使用Fisher-Yates 算法在 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;
   }
}
于 2010-09-15T14:00:04.387 回答