Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <blockquote> <p>@palmsey: In fairness to the OP, the javascript docs actually explicitly refer to using variables of type Object in this manner as "associative arrays".</p> </blockquote> </blockquote> <p>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: </p> <p><a href="http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/" rel="nofollow noreferrer">JavaScript “Associative Arrays” Considered Harmful</a></p> <p>But according to all this, isn't the <a href="https://stackoverflow.com/questions/5223/length-of-javascript-associative-array#5234">accepted answer</a> itself bad practice?</p> <blockquote> <blockquote> <p>Specify a prototype size() function for Object</p> </blockquote> </blockquote> <p>If anything else has been added to Object .prototype, then the suggested code will fail:</p> <pre><code>&lt;script type="text/javascript"&gt; 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()); &lt;/script&gt; </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload