最高效的数组洗牌器 [英] Most efficient array shuffler
本文介绍了最高效的数组洗牌器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何以最有效的方式打乱数组的值?
How can I shuffle an array's values in the most efficient manner possible?
每个元素只是一个包含 HTML 的字符串.
Each element is just a string containing HTML.
推荐答案
您有几个选择.
首先,您可以使用愚蠢的分拣机...
First, you could use the stupidely naïve sorter...
arr = arr.sort(function() {
return Math.random() - .5
});
这是快速而肮脏的,但通常被认为是不好的做法.
This is quick and dirty but often considered bad practice.
随机排序 Array
的最佳方法是使用 Fisher-Yates 随机播放.
The best way to randomly sort an Array
is with the Fisher-Yates shuffle.
var newArr = [];
while (arr.length) {
var randomIndex = Math.floor(Math.random() * arr.length),
element = arr.splice(randomIndex, 1)
newArr.push(element[0]);
}
这篇关于最高效的数组洗牌器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文