只是一些jQuery片段的共享,以便以随机顺序显示/排序事物。
排序代码段
以对象字面量格式使用此功能。
shuffleAds: function(arr)
{
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
}
另一个功能做同样的事情。
function randsort(c) {
var o = new Array();
for (var i = 0; i < c; i++) {
var n = Math.floor(Math.random()*c);
if( jQuery.inArray(n, o) > 0 ) --i;
else o.push(n);
}
return o;
}
还认为这个jQuery Shuffle插件值得包括在内。
/* * jQuery shuffle * * Copyright (c) 2008 Ca-Phun Ung
* Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://yelotofu.com/labs/jquery/snippets/shuffle/ * * Shuffles an array or the children of a element container. * This uses the Fisher-Yates shuffle algorithm
*/ (function($){ $.fn.shuffle = function() { return this.each(function(){ var items = $(this).children().clone(true); return (items.length) ? $(this).html($.shuffle(items)) : this; }); } $.shuffle = function(arr) { for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x); return arr; } })(jQuery);
From: https://www.sitepoint.com/jquery-output-array-random-order/