Why does an array allow a string as an index in JavaScript? [closed]
2
As we already know, one of the differences between an array and object is:
"If you want to supply specific keys, the only choice is an object. If you don't care about the keys, an array it is" (Read more here)
Besides, according to MDN's documentation:
Arrays cannot use strings as element indexes (as in an associative array) but must use integers
However, I was surprised that:
> var array = ["hello"]; // Key is numeric index
> array["hi"] = "weird"; // Key is string
content structure looks like: ["hello", hi: "weird"]
The content structure of the array looks weird.
Even more, when I check the type of array it returns true
Array.isArray(array) // true
Questions:
- Why have this behavior? This seems inconsistent, right?
- What is the data structure actually storing behind the scene: as an array or something like an object, hash table, linked list?
- Does this behavior depend on a specific JavaScript engine (V8, spidermonkey, etc..) or not?
- Should I use arrays like this (keys are both numeric index and string) over normal objects?
javascript arrays object
-
2It's possible to create arbitrary properties on array objects, but you should absolutely not do this. They are not associative arrays. – Bergi Apr 10 at 2:03
-
1My TL;DR answer would be… (1) On the surface, it does seem inconsistent, but it's actually very consistent when you take a deeper look. (2) the array is an array, even behind the scenes, but arrays in JS are a type of object and thus can be assigned custom properties in addition to array elements. (3) Nope! This is just pure JavaScript. (4) If you require keys to be numeric and alphanumeric, use an object. HOWEVER, if you would like to use an array, it's perfectly okay to add custom properties to that array as well. Just keep in mind they are only properties of the object, not array elements. – Brandon McConnell Apr 15 at 17:33
-
1@NguyễnVănPhong Also, I didn't include this in my answer, but if you require keys, and you also want to maintain the insertion order of your keys (since JS objects cannot reliably retain their property order), consider using a Map object-type instead. Further research: Map() to the rescue; adding order to Object properties – Brandon McConnell Apr 15 at 17:38
-
3@NguyễnVănPhong By that metric, i also see no useful answers here. ¯\_(ツ)_/¯ More words doesn't make the question or answer more useful. The TLDR of everything here is arrays are objects, but should never be used as objects. The "why" is because arrays are objects. Nothing else is useful or programming related. – Kevin B Apr 20 at 14:25
-
1To be honest, I get the useful answer from @VLAZ 's summary, research over the other ones. – Nguyễn Văn Phong Apr 22 at 12:35
|
Show 9 more comments