JavaScript - 在对象内部洗牌对象(随机化)

时间:2010-09-15 13:51:57

标签: javascript json object shuffle random

我需要从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...]

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

3 个答案:

答案 0 :(得分:27)

您可以使用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;
}

答案 1 :(得分:8)

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

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 :(得分: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;
   }
}