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

JavaScript method to calculate object length

小云云
Release: 2017-12-09 14:22:49
Original
1400 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 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
Copy after login

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

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!

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!