How to efficiently count the number of keys/proper

2019-08-03 16:37发布

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.)

20条回答
聊天终结者
2楼-- · 2019-08-03 17:03

For those who have Underscore.js included in their project you can do:

_({a:'', b:''}).size() // => 2

or functional style:

_.size({a:'', b:''}) // => 2
查看更多
看我几分像从前
3楼-- · 2019-08-03 17:05

If jQuery above does not work, then try

$(Object.Item).length
查看更多
不美不萌又怎样
4楼-- · 2019-08-03 17:06

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;
查看更多
smile是对你的礼貌
5楼-- · 2019-08-03 17:06

OP didn't specify if the object is a nodeList, if it is then you can just use length method on it directly. Example:

buttons = document.querySelectorAll('[id=button)) {
console.log('Found ' + buttons.length + ' on the screen'); 
查看更多
孤傲高冷的网名
6楼-- · 2019-08-03 17:07

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:

if (myobj.__count__ === undefined) {
  myobj.__count__ = ...
}

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:

if (myobj.__count__ === undefined) {
  myobj.__count__ = function() { return ... }
  myobj.__count__.toString = function() { return this(); }
}

This way anytime you reference myobj.__count__ the function will fire and recalculate.

查看更多
神经病院院长
7楼-- · 2019-08-03 17:07

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.

查看更多
登录 后发表回答