Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Simple enough:</p> <pre><code>for(var propertyName in myObject) { // propertyName is what you want // you can get the value like this: myObject[propertyName] } </code></pre> <p>Now, you will not get private variables this way because they are not available.</p> <hr> <p>EDIT: <a href="https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306">@bitwiseplatypus</a> is correct that unless you use the <code>hasOwnProperty()</code> method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.</p> <p>Now, that said, <code>hasOwnProperty()</code> <em>is</em> useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.</p> <p>EDIT 2: <a href="https://stackoverflow.com/questions/85992/how-do-i-enumerate-the-properties-of-a-javascript-object#86306">@bitwiseplatypus</a> brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use <code>hasOwnProperty()</code>. Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via <code>jQuery.extend</code> and <code>jQuery.fn.extend</code>).</p>
    singulars
    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