Can some one please explain to me in a layman's what is happening in the loop as it iterates to produce the statement (the objects properties are in an array).
var o = {x:1, y:2, z:3};
var a = [], i = 0;
for (a[i++] in o)
{
console.log(o);
}
Can some one please explain to me in a layman's what is happening in the loop as it iterates to produce the statement (the objects properties are in an array).
var o = {x:1, y:2, z:3};
var a = [], i = 0;
for (a[i++] in o)
{
console.log(o);
}
This is how the for/in loop is evaluated:
for each property in object o
assign the property name to the left hand side, that is a[i++]
Initially i = 0, so:
a[0] will get x. // notice it gets the property name, not its valuea[1] will get y.a[2] will get z.NOTE: i++ is equal to i = i + 1.
The previous code is equivalent to the following:
var o = {x:1, y:2, z:3};
var a = []
var i = 0;
for (propertyName in o)
{
a[i] = propertyName;
i = i + 1;
console.log(o);
}
It assigns an object with three keys (x,y,z) to o. It assigns an empty array to a, and the number 0 to i.
The for ( in ) loop will iterate over an object's properties, but first the condition is evaluated.
i++ is evaluated first. The ++ is a post-increment operator and is notorious for people getting the damn thing wrong. Douglass Crockford (search for him) suggests not using it. It returns the value stored in i (which was 0) then increments it.
So now i is storing 1, and we're evaluating a[0], which is accessing an element in an array, except... that array is empty (we're accessing an undefined value).
It now looks at in o, which iterates through the keys in o, which there are 3 of. Thus, it iterates the loop three times. Each time it then logs the object to the console.
Whatever this code is, I'd suggest replacing it. It shouldn't be something you want to see in code. It's confusing and surely doesn't do anything meaningful.