如何获取对象长度 [英] How to get object length
问题描述
有没有可以返回对象长度的内置函数?
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() 你可以简单地做:
For browsers supporting Object.keys() you can simply do:
Object.keys(a).length;
否则(尤其是在 IE < 9 中),您可以自己使用 for (x in y)
循环遍历对象:
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屋!