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

How to calculate the length of the obtained object in JS

php中世界最好的语言
php中世界最好的语言Original
2018-04-16 17:37:416338browse

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

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
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!

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