What's the fastest way to count the number of keys/properties of an object? It it possible to do this without iterating over the object? i.e. without doing
var count = 0;
for (k in myobj) if (myobj.hasOwnProperty(k)) count++;
(Firefox did provide a magic __count__
property, but this was removed somewhere around version 4.)
For those who have Underscore.js included in their project you can do:
or functional style:
If jQuery above does not work, then try
You could use this code:
Then you can use this in older browsers as well:
OP didn't specify if the object is a nodeList, if it is then you can just use length method on it directly. Example:
I'm not aware of any way to do this, however to keep the iterations to a minimum, you could try checking for the existance of
__count__
and if it doesn't exist (ie not Firefox) then you could iterate over the object and define it for later use eg:This way any browser supporting
__count__
would use that, and iterations would only be carried out for those which don't. If the count changes and you can't do this, you could always make it a function:This way anytime you reference myobj.
__count__
the function will fire and recalculate.I don't think this is possible (at least not without using some internals). And I don't think you would gain much by optimizing this.