如何高效地计算JavaScript中的对象的键/属性的数量? [英] How to efficiently count the number of keys/properties of an object in JavaScript?
本文介绍了如何高效地计算JavaScript中的对象的键/属性的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
计算对象的键/属性数量的最快方法是什么?它有可能做到这一点,而不迭代的对象?即不做
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提供了一个神奇的 __ count __
属性,
(Firefox did provide a magic __count__
property, but this was removed somewhere around version 4.)
推荐答案
要在任何ES5兼容的环境中执行此操作,例如节点,Chrome,IE 9+,FF 4+或Safari 5 +:
To do this in any ES5-compatible environment, such as Node, Chrome, IE 9+, FF 4+, or Safari 5+:
Object.keys(obj).length
- 浏览器兼容性
- Object.keys文档
- (包括您可以添加到非ECMA5浏览器的方法)
这篇关于如何高效地计算JavaScript中的对象的键/属性的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文