更新时间:2022-12-11 20:45:05
旧的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;
}