I found this code online for shuffling array elements, it works well, but I can’t understand the for loop here
shuffle = function(o)
{
for(var j, x, i = o.length; i;
j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
any help is appreciated, thank you !
This is basically a misuse of the flexibility of the
forloop.The general syntax for a
forloop is:which roughly can be expressed as following
whileloop:Since both
<body>and<increment>are both executed as if they were in the body of thewhile, anything that can go into the body of aforloop, can also be put in the<increment>expression of theforloop. You just have to separate the statements with commas instead of semicolons.Thus your
forloop is probably better expressed as followingwhileloop: