JavaScript - 在对象内打乱对象(随机化)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3718282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - Shuffling Objects inside an object (randomize)
提问by easement
I need to implement a randomization from JSON result.
我需要从 JSON 结果实现随机化。
The format of the JSON is two objects:
JSON 的格式是两个对象:
result:
结果:
Question(object)
问题(对象)
[Object { id="4c6e9a41470b19_96235904", more...},
Object { id="4c784e6e928868_58699409", more...},
Object { id="4c6ecd074662c5_02703822", more...}, 6 more...]
Topic(object)
主题(对象)
[Object { id="3jhf3533279827_23424234", more...},
Object { id="4634663466cvv5_43235236", more...},
Object { id="47hf3892735298_08476548", more...}, 2 more...]
I want to randomize the order of the objects inside the question object and the topic objects.
我想随机化问题对象和主题对象中对象的顺序。
回答by LukeH
You could use a Fisher-Yates-Durstenfeld shuffle:
您可以使用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;
}
回答by pepkin88
Easiest method (not perfect shuffle, but in some cases may be better):
最简单的方法(不是完美的 shuffle,但在某些情况下可能会更好):
function randomize(a, b) {
return Math.random() - 0.5;
}
yourQuestionArray.sort(randomize);
yourTopicArray.sort(randomize);
or
或者
yourQuestionArray.sort(function (a, b) {return Math.random() - 0.5;});
yourTopicArray.sort(function (a, b) {return Math.random() - 0.5;});
回答by gnarf
I found this poston using the Fisher-Yates algorithmto shuffle an array in JavaScript. It uses this function:
我发现这篇关于使用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;
}
}