So I was reading about shuffling an array. And then I came across this script:
shuffle = function(o){ //v1.0
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;
};
When I look closely, the for does not even have any {} at all! But it is working, like magic. I am very curious to know how it work. (and the bunch of commas too.)
What follows the
for ()can be any statement; that can be something with curly braces, or it can be a single expression, or it can be an empty expression.for (...);is equivalent tofor (...) {}. Naturally, this should only be used in conjunction with a for-loop which will terminate naturally, or you’ll have an infinite loop on your hands.The commas are effectively second-grade semicolons; they make for mostly-separate statements, but which will work in a for loop (and elsewhere; this is a very sloppy definition of them).
This could be put in a more readable form as:
As a while loop, that could be: