Consider the following code:
var arr = [];
arr["abc"] = 1;
arr["bcd"] = 2;
console.log(arr.length); // outputs 0
arr["1"] = "one"; // notice the subscript content is in quotes
console.log(arr.length); // outputs 2
console.log(arr); // outputs [undifined, "one"]
console.log(arr["abc"]); // outputs 1
In the above program, I have defined the array arr
which is first assigned with string indexes, so the array length stays 0. I read somewhere that when string value is used for subscript, the array object is treated as an ordinary object. So, I can understand if the length is zero (Should probably be undefined).
Then, when I use a subscript of "1"
, which should be of string type is taken as a Number and the length is incremented. Then when the array is printed there is a value of undefined for the index 0
and index 1
has the value "one"
( Note that the indexes "abc"
and "bcd"
are not shown when printed.
Finally, when I try to access the "abc"
value, I get the value.
So my questions are the following:
- What happens when an array is assigned with a string index and why does the length remain the same?
- Does the javascript interpreter tries convert the index to a Number before using it?
- Where are the values of the array string indexes stored and why are they not shown when I try to print the array?
- Finally, can someone point me to a good article which explains the implementation details of javascript's features.
Thanks in advance.