Javascript Array Object vs Array Like Objects - Clarification
The difference is the indexes. When you use an array []
the indexes can only be positive integers.
So the following is wrong:
var array = [ ];array['test1'] = 'test 1';array['test2'] = 'test 2';
because test1
and test2
are not integers. In order to fix it you need to use integer based indexes:
var array = [ ];array[0] = 'test 1';array[1] = 'test 2';
or if you declare a javascript object then the properties can be any strings:
var array = { };array['test1'] = 'test 1';array['test2'] = 'test 2';
which is equivalent to:
var array = { };array.test1 = 'test 1';array.test2 = 'test 2';
You don't want an array. When you want an "associative array" in JavaScript, you really want an object, {}
.
You can distinguish them with instanceof Array
:
[] instanceof Array // true({}) instanceof Array // false
EDIT: it can process it. It serializes all of the elements of the array. However, to be an element, there must be a numeric key. In this case, there are none.
This is nothing unique to JSON. It's consistent with toSource
and the length
property.
"Can someone shed some light or some reference where I can read more?"
When you're dealing with JSON
data, you can refer to json.org to read about the requirements of the specification.
In JSON
, an Array
is an order list of values separated by ,
.
So the JSON.stringify()
is simply ignoring anything that couldn't be represented as a simple ordered list.
So if you do...
var simpleArray = [];simpleArray.foo = 'bar';
...you're still giving an Array, so it is expecting only numeric indices, and ignoring anything else.
Because JSON
is language independent, the methods for working with JSON
need to make a decision about which language structure is the best fit for each JSON
structure.
So JSON has the following structures...
{} // object[] // array
You should note that though the look very similar to JavaScript
objects and arrays, they're not strictly the same.
Any JavaScript
structures used to create JSON
structures must conform to what the JSON
structures will allow. This is why the non-numeric properties are removed excluded.
While JavaScript
doesn't mind them, JSON
won't tolerate them.