Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - 如何获取对象长度[重复](How to get object length [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

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

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

For example, I have a = { 'a':1,'b':2,'c':3 } which should return 3 .

(例如,我有a = { 'a':1,'b':2,'c':3 }应返回3 。)

If I use a.length it returns undefined .

(如果我使用a.length则返回undefined 。)

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

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

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.

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

  ask by Larry Cinnabar translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For browsers supporting Object.keys() you can simply do:

(对于支持Object.keys()的浏览器,您只需执行以下操作:)

Object.keys(a).length;

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

(否则(特别是在IE <9中),您可以使用for (x in y)循环自行遍历对象:)

var count = 0;
var i;

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

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.

(hasOwnProperty用于确保您只计算来自对象文字的属性,而不是它从其原型“继承”的属性。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...