How to efficiently count the number of keys/properties of an object in JavaScript

2k2008 年提問 · mjs ·javascriptperformancepropertiescountkey 主題:物件、JSON 與拷貝 → 在 Stack Overflow 看原文 ↗

What’s the fastest way to count the number of keys/properties of an object? Is 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.)

重點答案

You could use this code:

if (!Object.keys) {
    Object.keys = function (obj) {
        var keys = [],
            k;
        for (k in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, k)) {
                keys.push(k);
            }
        }
        return keys;
    };
}

Then you can use this in older browsers as well:

var len = Object.keys(obj).length;

If you are using Underscore.js you can use _.size (thanks douwe):

_.size(obj)

Alternatively you can also use _.keys which might be clearer for some:

_.keys(obj).length

I highly recommend Underscore.js. It's a tight library for doing lots of basic things. Whenever possible, they match ECMAScript 5 and defer to the native implementation.

Otherwise I support Avi Flax' answer. I edited it to add a link to the MDC documentation which includes the keys() method you can add to non-ECMAScript 5 browsers.