javascript - Understanding this jQuery .shuffle() plugin or function -
could please me understand how jquery plug-in works. don't understand how .shuffle() method works. here jsbin link http://jsbin.com/yefofulohu/2/edit
jquery(function($){ // unordered list $('button').click(function(){ $('ul').shuffle(); }); }); (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, = arr.length; i; j = parseint(math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x); return arr; } })(jquery);
understanding for loop's syntax understand what's happening:
for(init (optional); condition (optional); final expression (optional)) statement (optional) though for loops typically used specific syntax (var = 0; < arr.length; i++), can leave out or of expressions (as author of function did) , more single operation within each expression. here more verbose version of $.shuffle function commented:
$.shuffle = function(arr) { for(var = arr.length; > 0; i--) { // random index var j = parseint(math.random() * i); // x = next element var x = arr[ - 1 ]; // next element = random element arr[ - 1 ] = arr[j]; // random element = next element's previous value arr[j] = x; } return arr; } instead of long-form method, opted setup variables in init expression, check i in condition expression (since decrementing, loop stop @ 0), , perform decrement , assignments in final expression.
Comments
Post a Comment