Finding the number of keys in an object
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How to efficiently count the number of keys/properties of an object in JavaScript?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | var values = [{ 'SPO2': 222.00000, 'VitalGroupID': 1152, 'Temperature': 36.6666666666667, 'DateTimeTaken': '/Date(1301494335000-0400)/', 'UserID': 1, 'Height': 182.88, 'UserName': null, 'BloodPressureDiastolic': 80, 'Weight': 100909.090909091, 'TemperatureMethod': 'Oral', 'Resprate': null, 'HeartRate': 111, 'BloodPressurePosition': 'Standing', 'VitalSite': 'Popliteal', 'VitalID': 1135, 'Laterality': 'Right', 'HeartRateRegularity': 'Regular', 'HeadCircumference': '', 'BloodPressureSystolic': 120, 'CuffSize': 'XL' }]; for (i=0; i < values.length; i++) { alert(values.length) // gives me 2. |
如何找到我的对象有多少个键?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | var value = { 'SPO2': 222.00000, 'VitalGroupID': 1152, 'Temperature': 36.6666666666667, 'DateTimeTaken': '/Date(1301494335000-0400)/', 'UserID': 1, 'Height': 182.88, 'UserName': null, 'BloodPressureDiastolic': 80, 'Weight': 100909.090909091, 'TemperatureMethod': 'Oral', 'Resprate': null, 'HeartRate': 111, 'BloodPressurePosition': 'Standing', 'VitalSite': 'Popliteal', 'VitalID': 1135, 'Laterality': 'Right', 'HeartRateRegularity': 'Regular', 'HeadCircumference': '', 'BloodPressureSystolic': 120, 'CuffSize': 'XL' }; alert(Object.keys(value).length); |
尝试
1 | Object.keys(values).length |
请参见:https://developer.mozilla.org/en/javascript/reference/global_objects/object/keys
为了兼容性
1 2 3 4 5 6 7 | if(!Object.keys) Object.keys = function(o){ if (o !== Object(o)) throw new TypeError('Object.keys called on non-object'); var ret=[],p; for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p); return ret; } |
或使用:
1 2 3 4 5 | function numKeys(o){ var i=0; for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)){ i++}; return i; } |
1 2 3 4 5 6 7 | function numKeys(o) { var res = 0; for (var k in o) { if (o.hasOwnProperty(k)) res++; } return res; } |
或者,在较新的浏览器中:
1 2 3 | function numKeys(o) { return Object.keys(o).length; } |
在您的示例中,
您可以迭代并只计算:
1 2 3 | var i = 0; for(var key in values[0]) if(values[0].hasOwnProperty(key)) i++; // now i is amount |