Namely, how does the following code:
var sup = new Array(5);
sup[0] = 'z3ero';
sup[1] = 'o3ne';
sup[4] = 'f3our';
document.write(sup.length + "<br />");
output '5' for the length, when all you've done is set various elements?
My 'problem' with this code is that I don't understand how length
changes without calling a getLength()
or a setLength()
method. When I do any of the following:
a.length
a['length']
a.length = 4
a['length'] = 5
on a non-array object, it behaves like a dict / associative array. When I do this on the array object, it has special meaning. What mechanism in JavaScript allows this to happen? Does javascript have some type of property system which translates
a.length
a['length']
into "get" methods and
a.length = 4
a['length'] = 5
into "set" methods?
If you're intending to implement objects with array-like access, the Array Mozilla dev center article is a great resource. Unfortunately I don't know the in depth details of Array implementation but there are a lot of details in that article.
It is important to know that when you do
sup['look'] = 4;
you are not using an associative array, but rather modify properties on the object sup. It is equivalent tosup.look = 4;
since you can dynamically add properties on javascript objects at any time.sup['length']
would for an instance output 5 in your first example.