本文介绍了如何有效地计算 JavaScript 中对象的键/属性的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
计算对象的键/属性数量的最快方法是什么?是否可以在不迭代对象的情况下执行此操作?即,不做:
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 确实提供了一个神奇的 __count__ 属性,但它在版本 4 左右的某个地方被删除了.)
(Firefox did provide a magic __count__ property, but this was removed somewhere around version 4.)
推荐答案要在任何ES5 兼容环境,例如 Node.js、Chrome、Internet Explorer 9+、Firefox 4+ 或 Safari 5+:
To do this in any ES5-compatible environment, such as Node.js, Chrome, Internet Explorer 9+, Firefox 4+, or Safari 5+:
Object.keys(obj).length- 浏览器兼容性
- Object.keys 文档(包括可以添加到非 ES5 浏览器的方法)
- Browser compatibility
- Object.keys documentation (includes a method you can add to non-ES5 browsers)
更多推荐
如何有效地计算 JavaScript 中对象的键/属性的数量
发布评论