@palmsey: In fairness to the OP, the javascript docs actually explicitly refer to using variables of type Object in this manner as "associative arrays".
And in fairness to @palmsey he was quite correct, they aren't associative arrays, they're definitely objects :) - doing the job of an associative array. But as regards the wider point you definitely seem to have the right of it according to this rather fine article I found:
JavaScript “Associative Arrays” Considered Harmful
But according to all this, isn't the accepted answer itself bad practice?
Specify a prototype size() function for Object
If anything else has been added to Object .prototype, then the suggested code will fail:
<script type="text/javascript">
Object.prototype.size = function () {
var len = this.length ? --this.length : -1;
for (var k in this)
len++;
return len;
}
Object.prototype.size2 = function () {
var len = this.length ? --this.length : -1;
for (var k in this)
len++;
return len;
}
var myArray = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;
alert("age is " + myArray["age"]);
alert("length is " + myArray.size());
</script>
I don't think that answer should be the accepted one as it can't be trusted to work if you have any other code running in the same execution context. To do it in a robust fashion surely you would need to define the size method within myArray and check for the type of the members as you iterate through them.