javascript随机排序列表 [英] javascript Sort list randomly
本文介绍了javascript随机排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
猜我有一个下一个列表:
guess I have a list with the next:
20 22 24
如何对三个元素进行随机排序,以便获得22、20、24或24、20、22之类的东西?
how can I sort the three elements randomly so I get stuff like 22, 20, 24 or 24,20,22?
我知道您可以生成随机数,但我想我不是要找那个吗?
I know you can generate random numbers but I think I'm not looking for that?
推荐答案
例如,您需要实现随机播放算法
You'll need to implement a shuffle algorithm, for example
var arr = [20, 22, 24];
function shuffleArray(a) { // Fisher-Yates shuffle, no side effects
if(a.length === 0) return a;
var i = a.length, t, j;
a = a.slice();
while (--i) t = a[i], a[i] = a[j = ~~(Math.random() * (i+1))], a[j] = t;
return a;
}
shuffleArray(arr); // [22, 24, 20]
shuffleArray(arr); // [22, 20, 24]
shuffleArray(arr); // [24, 22, 20]
这篇关于javascript随机排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文