The difference between a JavaScript Array
, and Object
is not very big. In fact it seems Array
mainly adds the length
field, so you can use both Array
s and Object
s as numeric arrays:
var ar = new Array();
ar[0] = "foo";
ar["bar"] = "foo";
var ob = new Object();
ob[0] = "foo";
ob["bar"] = "foo";
assert(ar[0] == ob[0] == ar["0"] == ob["0"] == ar.bar == ob.bar); // Should be true.
So my questions is, in popular JavaScript engines (V8, JavaScriptCore, SpiderMonkey, etc.), how is this handled? Obviously we do not want our arrays to be actually stored as hash maps with key values! How can we be reasonably sure our data is stored as an actual array?
As far as I can see there are a few approaches engines could take:
Array
is implemented exactly the same way asObject
- as an associative array with string keys.Array
is a special case, with astd::vector
-like array backing the numeric keys, and some density heuristic to prevent insane memory use if you doar[100000000] = 0;
Array
is the same asObject
, and all objects get a heuristic to see if using an array would make more sense.- Something insanely complicated that I haven't thought of.
Really this would be simpler if there were a proper array type (cough WebGL typed arrays cough).
length
property tacked on. If it were, then shifting or unshifting would break the indexing (i.e. shift a value off an array, and it still starts at index 0, not 1). So there's at least a little more going on. (Not that this necessarily says anything about the implementation, of course)r[0] == ob[0] == ar["0"] == ob["0"] == ar.bar == ob.bar
to be true?'a' == 'a' == 'a'
is false because it evaluates totrue == 'a'
which evaluates tofalse
.shift
is implemented as a generic method, not array specific. It will work perfectly well with a regular object. Shifting works because it grabs the first value, then loops over all values assigning left and finally deletes the last element and sets length.var a = { 0: 0, 1: 1, length: 2 }; Array.prototype.shift.apply(a); alert(JSON.stringify(a))
. You should reliably get{"0":1,"length":1}
.