Home > Web Front-end > JS Tutorial > How to calculate the length of the obtained object in JS

How to calculate the length of the obtained object in JS

php中世界最好的语言
Release: 2018-04-16 17:37:41
Original
6346 people have browsed it

This time I will show you how to calculate and obtain the length of object with JS. What are the precautions for calculating and obtaining the length of object with JS. The following is a practical case. Let’s take a look. take a look.

Calculate the length of the object, that is, get the number of attributes of the object, as follows

Method 1: Traverse the object through for in , and determine whether it is an enumerable property of the object itself through hasOwnProperty

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 array composed of the enumerable attributes of the object through Object.keys(), 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
I believe I have read the case in this article You have mastered the method. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Vue array and object assignment issues

Bootstrap and Vue operation user information addition and deletion

The above is the detailed content of How to calculate the length of the obtained object in JS. 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