Using Array object in this manner feels very, very wrong. It completely removes the benefits of Array class and adds no value whatsoever.
The whole point of using arrays is to.. well.. treat them like arrays. So you get access to goodies such as push
, pop
, shift
, splice
, sort
, join
, .length
etc.
Just consider what happens when you add few properties to your array this way:
var test = new Array();
test.prop1 = 'hi';
test.prop2 = 'ho';
test.prop3 = 'ha';
test.length; // returns 0
test.join() // returns ""
test.pop() // returns undefined ... and so on
You completely obliterated the true function of an array.
Even looping through this monstrosity is not trivial, as you need to pass each property through hasOwnProperty
to check if it is a property you set, or is it something coming from Array.prototype. - as Doorknob pointed out internal array properties are not visible.
I'm not even going to start with what happens when someone tries to assign a property called length
on this object, etc.
Now, there is a right way to store properties like this, using a simple Object.
var test = {};
test.prop1 = 'hi';
test.prop2 = 'ho';
test.prop3 = 'ha';
Here, you can still loop through it retrieving the keys and values but most important part of this syntax and what it is often used for, is that you can look up value directly, without looping: test['prop1']
. This is great, because you don't have to loop through big object/array to find the property you're looking for.
So once again - if you want to store bunch of values and treat them as an array where you can add/remove items easily and use .length
to check number of elements etc - use Array
class.
If you want to access item directly by the key, and you don't need any of the array functionality (think hashmap), use simple Object
.
But for God's sake do not use Array
class for your hashmap base.
key:value
pairs.