5
BUG?
I was building a library for Arrays treatment and came across the following situation: When including a value to a negative index within my Array, this index does not appear when using some methods:
Example:
var array = new Array("Maria", "João", "Carlos");
array[-3] = "Bernardo";
console.log(array[-3]); //Bernardo
console.log(array.length); //3
console.log(JSON.stringify(array)); //"["Maria", "João", "Carlos"]"
Note that the quantity remains as 3 when using length
and the method JSON.stringify
shows only the original 3, however, when displaying on the console the array[-3]
the name comes correctly.
Question:
It wouldn’t be right to show up length = 4
and appear in the method JSON.stringify
? Why does this happen? Would it be some kind of bug the language allow me to add a value to a negative index?
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
-3
is 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
null
andundefined
as 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
Map
andWeakMap
, who will accept objects of truth as keys.– bfavaretto