如何获取JavaScript对象中的字段数? [英] How do I get number of fields in JavaScript object?
问题描述
我正在尝试将JavaScript对象用作关联数组,一切都很顺利,直到我需要获取存储在其中的条目数。最简单,最优雅的方法是什么?我能想到的是为每个循环或jQuery $。每个
函数运行,看看它有多少次迭代会这样做但看起来很糟糕。
I'm trying to use JavaScript object as an associative array and everything was well until I needed to get number of entries that are stored in it. What is the easiest and most elegant way to do that? All I can think of is to run for each
loop or jQuery $.each
function and just see how much iterations it would do but that looks like an an awful thing to do.
推荐答案
旧的Firefox支持 __ count __
property。较新的环境支持ES5的 Object.keys
。对于较旧的环境,我们必须回退到迭代对象并手动计数(呃!):
Old Firefox supports the __count__
property. Newer environments support ES5's Object.keys
. For older environments we have to fallback to just iterating over the object and counting manually (ugh!):
function count(obj) {
if (obj.__count__ !== undefined) { // Old FF
return obj.__count__;
}
if (Object.keys) { // ES5
return Object.keys(obj).length;
}
// Everything else:
var c = 0, p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
c += 1;
}
}
return c;
}
这篇关于如何获取JavaScript对象中的字段数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!