The method for calculating the object length in javascript.

Source: Internet
Author: User
Tags hasownproperty

The method for calculating the object length in javascript.

Calculates the length of an object, that is, the number of Object Attributes. The details are as follows:

Method 1:Traverse an object through for in and use hasOwnProperty to determine whether it is an object's own enumerable property.

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); // The result is 2.

Method 2:Use Object. keys () to obtain an array composed of the enumerated attributes of an Object, and use length to obtain the Object length.

Var obj = {"c1": 1, "c2": 2}; var arr = Object. keys (obj); var len = arr. length; console. log (len); // The result is 2.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.