Home >Web Front-end >JS Tutorial >How to calculate object length in javascript

How to calculate object length in javascript

小云云
小云云Original
2018-01-22 09:03:492272browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn