I found the reply of @mgibsonbr correct but a little confusing. I will leave my contribution, a translation and adaptation of an answer of Soen, which makes it more evident to Javascript donkeys like me. >.<
When you directly reference an index or position, the values are added to the array:
var array = [];
array[0] = "Foo";
array[1] = "Bar";
// Result: ["Foo", "Bar"]
// Length: 2
What is not the case when referencing negative indices:
var array = [];
array[0] = "Foo";
array[1] = "Bar";
array[-1] = "Fizzbuzz"; // Índice inválido - Pega, Rex! Pega!
// Result: ["Foo", "Bar"]
// Length: 2
Values will only be added if you play by the rules. If you do not follow them, values will not be added. Simple as that!
But although not accepted as part of the data set, information associated with negative evidence is accepted by Array object and so it is still possible to access this value, like any other property:
array[-1]; // "Fizzbuzz"
When we build an Array object, even if we have not defined any value for it, it is not empty; after all, all methods belonging to the object, whether native or prototyped, are already there at disposal and can even be accessed in the same way:
array["pop"]; // function pop() { [native code] }
Here we access the index prop which is not a valid index for data collection, but is valid as property of the Array object and is associated with native code Array.pop().
And so property as length and methods such as Array.prototype.pop() or Array.prototype.Slice(), working solely with integer and positive indices show different results than you expect.
Again, to reinforce. The value is not in the array and yes in the object Array.
A link to Ecmascript description would be nice! Rsrs. I didn’t know that Javascript and Actionscript were provided with this language, now it becomes even clearer the similarity between them. Regarding Array, I now understand that
-3is treated as"-3"being a value of an Object and not an index of an Array and that the Array object of languages are also a "subtype" of a common object.– bio
I also tested with Boolean value
array[true] = "Abner;", it treats like a 'normal object'! Very strange and at the same time interesting! Rsrs– bio
@Biio He accepts even
nullandundefinedas keys... : P (huge potential for errors, by the way)– mgibsonbr
But @biio, note that the key is always converted to string, so
"true","null"or"undefined".– bfavaretto
@bfavaretto Indeed. Inclusve, when using an object as a key (say,
arr[{ foo:"bar" }]) what is used is its representation as string (arr["[object Object]"]). Another potential for mistakes...– mgibsonbr
It is. In the next version (ES6), there will be
MapandWeakMap, who will accept objects of truth as keys.– bfavaretto