9 ms·
Javascript's arrays cannot be used as maps or associative arrays. Arrays require numeric, consecutive keys. Otherwise it's an Object. -- Clarification edit: C
by shimonamit 12y ago
Javascript's arrays cannot be used as maps or associative arrays. Arrays require numeric, consecutive keys. Otherwise it's an Object.
--
Clarification edit: Creating a new key on an array using arr['key']=1 creates a property on the arr Object but does not add an element to the standard array.
http://stackoverflow.com/questions/8630471/strings-as-keys-of-array-in-javascript http://stackoverflow.com/questions/8630471/strings-as-keys-o...
- mc808 12y agoArrays are always objects in JavaScript, and they can be extended like any other object or used as maps (barring key conflicts).
- dsp1234 12y agoAdding non-numeric keys does not remove an Array's "arrayness" in JavaScript var x = []; console.log(Object.prototype.toString.call(x)); //[object Array] x[0] = 1; console.log(x[0]); //1 x["test"] = 2; console.log(x["test"]); //2 console.log(Object.prototype.toString.call(x)); //[object Array] x.map //function map() { [native code] } var y = {}; console.log(Object.prototype.toString.call(y)); //[object Object] y.map //undefined
- the_mitsuhiko 12y agoIt does internally. Pretty sure that's even defined in the standard.
- cgrand-net 12y agoIf you can't observe a difference, does it matter?
- gsnedders 12y agoNo, it doesn't. The only magic per spec is about the "length" property (which is essentially a getter/setter pair, despite being a data property and not an accessor pair). That's the only thing special about arrays in JS.
- nothrabannosir 12y agoHis point was: x = [1]; x["test"] = 555; x.map(function (y) { return y; }); // [1] That's [1], not [1, 555]. You can access the array from the map interface, but not the other way around.
- dsp1234 12y agoThe array prototype functions are only specified by the standard to deal solely with numeric keys, but the lines between and object and array are still pretty blurry. The use case for each is different, but the original question far above was "array/map combo. Have you ever seen anything like that in another language?", and clearly JavaScript is very similar even if not exact. var x = {}; x[0] = 1; x.length = 1; x.map = Array.prototype.map; x.map(function(y) {return y;}); //[1]
- robocat 12y agoArrays are full objects e.g. function(){ var x = []; x.foo = "bar"; return x.foo;} returns "bar". That is the whole reason prototype.js library broke the use of for (var x in somearray) because the library set properties on Array.prototype.