Quote:
|
I do not fully understand why Javascript is unable to loop through the JSON object as if it were an array, especially when the top-dimension variables / keys are numbers (ie easily sortable). Can anyone elaborate on this in layman's terms?
|
Okay. In simplest possible terms:
An array is an array. An object with property values is not an array.
Just because we can use the same notation to access array elements as we can to access object properties does not make them the same. Heck, we use a period between the integer and fractional parts of a number, but that doesn't make the number
3.1415 the same as an
object.property reference. Similar syntax does not necessarily denote similar underlying capabilities.
Perhaps we could also point out that you can't give numbers to array elements as part of the expression on the right hand side of the assignment (=) operator.
That is, you must code
Code:
whatever[3] = "something";
never
Code:
whatever = [3,"something"];
or anything similar.
There's a *HUGE* difference between
Code:
whatever = [3,"something"];
and
whatever = { 3 : "something" };
The former creates an array of two elements: whatever[0]==3, whatever[1]=="something".
The latter creates an object with one property: whatever["3"]=="something".
Notice that I coded ["3"] there and not [3]. Actually,
whatever[3] would have worked, but of course it's very misleading in appearance. It's just another case of JS silently converting a number to a string for you.
Which is one reason that I avoid using object property names that look like numbers or even that start with digits.
For one thing, if you do
Code:
whatever = { "p3" : "something" };
Then you can code
alert( whatever.p3 )
Whereas if you do
Code:
whatever = { "3" : "something" };
Then KABLOOEY if you try to code
alert( whatever.3 )
So although your use of numbers-as-strings for the top-level property names in your JSON object works, it's not something I would ever do. If nothing else, I would give them a prefix (e.g., "item0" : {.... } ).