JavaScript - 在对象内部洗牌对象(随机化) [英] JavaScript - Shuffling Objects inside an object (randomize)
本文介绍了JavaScript - 在对象内部洗牌对象(随机化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从JSON结果实现随机化。
JSON的格式是两个对象:
<结果:
问题(对象)
[Object {id =4c6e9a41470b19_96235904,more ...},
Object {id =4c784e6e928868_58699409,more ...},
Object {id =4c6ecd074662c5_02703822,更多...},6更多...]
主题(对象)
[Object {id =3jhf3533279827_23424234,more ...},
Object {id =4634663466cvv5_43235236 ,更多...},
对象{id =47hf3892735298_08476548,更多...},2更多...]
我想随机化问题对象和主题对象内对象的顺序。
解决方案
您可以使用 Fisher-Yates-Durstenfeld shuffle :
var shuffledQuestionArray = shuffle(yourQuestionArray);
var shuffledTopicArray = shuffle(yourTopicArray);
// ...
函数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;
}
返回sourceArray;
}
I need to implement a randomization from JSON result.
The format of the JSON is two objects:
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.
解决方案
You could use a 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;
}
这篇关于JavaScript - 在对象内部洗牌对象(随机化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文