This article mainly introduces the method of calculating object length in JavaScript in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
Calculate the length of the object, that is, get the number of object properties, as follows
Method 1:Traverse the object through for in, and determine whether it is the object itself through hasOwnProperty Enumerable properties
var obj = {"c1":1,"c2":2}; function countProperties(obj){ for(var property in obj){ if(Object.prototype.hasOwnProperty.call(obj,property){ count++; }) } return count; } var len = obj.length; console.log(len);//结果为2
Method 2: Get the object’s enumerable properties through Object.keys() array, and get the object length through length
var obj = {"c1":1,"c2":2}; var arr = Object.keys(obj); var len = arr.length; console.log(len);//结果为2
Related recommendations:
JavaScript calculates characters The number of bytes occupied by the string
Decimal calculation problem in JavaScript tutorial
Detailed explanation of PHP's method of calculating time difference
The above is the detailed content of JavaScript method to calculate object length. For more information, please follow other related articles on the PHP Chinese website!