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 through hasOwnProperty It is the enumerable property of the object itself
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 length of the object through length
var obj = {"c1":1,"c2":2}; var arr = Object.keys(obj); var len = arr.length; console.log(len);//结果为2
Related recommendations:
How jQuery gets and calculates the object length?
Detailed explanation of the usage of this object in js
Detailed explanation of the properties of the jQuery event object
The above is the detailed content of How to calculate object length in javascript. For more information, please follow other related articles on the PHP Chinese website!