What did you expect to see? :) I'm not sure what you are trying to do.
x
is an array and everything you did when you did x.name
, you just created the name
property for the array object. The name
property is not added to the array. You can see this in firebug:
An array object has a name
property, but the value of this property is not added to the array itself.
What you want to do is something like this:
var x = { array: [1, 2, 3, 4], name: "myArray" };
You now have an object named x
that has two properties. The array
property refers to the array, and the name
property refers to the name. x.array
will give you an array, and x.name
will give you a name.
EDIT
This is the answer to your comments. Although it is true that arrays can be enriched with properties, think about what this means when you need to serialize this object. What exactly do you want to see when you serialize x
? If x
already an array [1, 2, 3, 4]
, how do you represent it in JSON? You can imagine it as:
{ 0: 1, 1: 2, 2: 3, 3: 4, name: "myArray" };
But you now have no array. In addition, the array object itself has a bunch of its own properties. How should the JSON serializer handle?
I think you are mixing an array as an object and an array as a literal. An array as a literal is simple [1, 2, 3, 4]
. Now, internally, an array as an object supposedly has some property that indicates the actual value of the array. It also has other properties (e.g. length
) and methods acting on it (e.g. slice
).
The JSON serializer is associated with the value of the object. If x
is an array, then the value to be serialized is the value of x
, which is [1, 2, 3, 4]
. The properties of x
completely different.
If you want to serialize these additional properties, you will have to write your own serializer, which will iterate over the properties of the array and represent everything in the map / associative array. This is the only way; the caveat, as I mentioned earlier, is that you no longer have the actual array.