如何有效地计算 JavaScript 中对象的键/属性的数量

编程入门 行业动态 更新时间:2024-10-12 12:34:21
本文介绍了如何有效地计算 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 中对象的键/属性的数量

本文发布于:2023-11-30 00:05:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648052.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有效地   属性   对象   数量   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!