Home > Web Front-end > JS Tutorial > body text

How to calculate object length in javascript

小云云
Release: 2018-01-22 09:03:49
Original
2203 people have browsed it

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!