Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:</p> <pre><code>Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; // Get the size of an object var size = Object.size(myArray); </code></pre> <p>There's a sort of convention in JavaScript that you <a href="https://stackoverflow.com/questions/10757455/object-prototype-is-verboten">don't add things to Object.prototype</a>, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.</p> <hr> <p><strong>Here's an update as of 2016 and <a href="http://kangax.github.io/compat-table/es5/" rel="noreferrer">widespread deployment of ES5</a> and beyond.</strong> For IE9+ and all other modern ES5+ capable browsers, you can use <code>Object.keys()</code> so the above code just becomes:</p> <pre><code>var size = Object.keys(myObj).length; </code></pre> <p>This doesn't have to modify any existing prototype since <code>Object.keys()</code> is now built in.</p> <p><strong>Edit</strong>: Objects can have symbolic properties which can not be returned via Object.key method. So the answer would be incomplete without mentioning them.</p> <p>Symbol type was added to the language to create unique identifiers for object properties. Main benefit of Symbol type is prevention of overwrites.</p> <p><code>Object.keys</code> or <code>Object.getOwnPropertyNames</code> does not work for symbolic properties. To return them you need to use <code>Object.getOwnPropertySymbols</code>.</p> <pre><code>var person = { [Symbol('name')]: 'John Doe', [Symbol('age')]: 33, "occupation": "Programmer" }; const propOwn = Object.getOwnPropertyNames(person); console.log(propOwn.length); // 1 let propSymb = Object.getOwnPropertySymbols(person); console.log(propSymb.length); // 2 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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