`I'm reading 'JavaScript: the definitive guide' and I'm getting hung up on an example:
“you can use code like the following to copy the names of all object properties into an array"
var o = {x:1, y:2, z:3};
var a = [], i = 0;
for(a[i++] in o) /* empty */;
I don't understand, why does the last line really do anything, without instructions. Why does it fill the array?
Wow, I'm actually surprised that this code works! Let me just say that I wouldn't recommend using it and would expect this sort of a[i++]
trickery to show up in ancient C, not in Javascript :)
As for why it works, it has to do with the syntax of the language. The syntax for a for Loop is:
for ( LeftHandSideExpression in Expression ) Statement
A LeftHandSideExpression is anything that you can assign to with the =
operator. In a for loop, usually we just use a variable identifier as in for(k in o)
but since arr[i]
is also a valid LHS expression (you can do arr[i] =
) we are also allowed to write for(arr[i] in o)
.
In the end, your loop does something similar to
var a=[], i=0;
a[i++] = "x";
a[i++] = "y";
a[i++] = "z";
// in the end, a should be ["x", "y", "z"]
// and i should be 3