如何获得对象长度 [英] How to get object length

查看:118
本文介绍了如何获得对象长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何可以返回对象长度的内置函数?

Is there any built-in function that can return the length of an object?

例如,我有 a = {'a ':1,'b':2,'c':3} 应返回 3 。如果我使用 a.length ,则返回 undefined

For example, I have a = { 'a':1,'b':2,'c':3 } which should return 3. If I use a.length it returns undefined.

它可能是一个简单的循环函数,但我想知道是否有内置函数?

It could be a simple loop function, but I'd like to know if there's a built-in function?

有一个相关的问题( JSON对象的长度) - 在所选答案中,用户建议将对象转换为数组,这是对我的任务不太满意。

There is a related question (Length of a JSON object) - in the chosen answer the user advises to transform object into an array, which is not pretty comfortable for my task.

推荐答案

对于支持 Object.keys()你可以做到:

Object.keys(a).length;

否则(特别是在IE< 9中),您可以使用<$自行循环访问对象c $ c> for(x in y) loop:

Otherwise (notably in IE < 9), you can loop through the object yourself with a for (x in y) loop:

var count = 0;
var i;

for (i in a) {
    if (a.hasOwnProperty(i)) {
        count++;
    }
}

hasOwnProperty 是为了确保你只计算来自对象文字的属性,而不是它从其原型继承的属性。

The hasOwnProperty is there to make sure that you're only counting properties from the object literal, and not properties it "inherits" from its prototype.

这篇关于如何获得对象长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆