JavaScript uses Object.keys to traverse object property names

Source: Internet
Author: User


In the actual development, we sometimes need to know all the attributes of the object, JS native gives us a good method: Object.keys, the method returns an array

var obj = {

' a ': ' 123 ',

' B ': ' 345 ',

};

Console.log (Object.keys (obj)); [' A ', ' B ']

It is noteworthy that if a string is passed in the keys method, the array is returned, except that the value in the array is the index of each character in the string:

var str = ' ab1234 ';

Console.log (Object.keys (obj)); [0,1,2,3,4,5]

example, traversing an array and traversing the object's differences

<script>     //----------------for traversing array objects-    var i,myarr
 = [1,2,3];     for  (var i = 0; i < myarr.length; i++)
 {        console.log (i+ ":" +myarr[i));
    };     //---------for-in  is used to traverse the     var man ={hands:2 of a non-array object.
LEGS:2,HEADS:1};     //adds a clone method to all objects, adding prototype properties to the built-in prototypes (Object,array,function), which is powerful and dangerous      if (typeof object.prototype.clone === "undefined") {         object.prototype.clone = function () {};         }      //    for (var i in man) {         if  (Man.hasownproperty (i))  { //filter, output only the private properties of man              console.log (i, ":", Man[i]);
        }; &NBSP;&NBSP;&NBSP;&NBSP}     //output to Print hands:2,legs:2,heads:1      for (Var i in man)  {//does not use filtration         
Console.log (i, ":", Man[i]);     }         //Output is     // Hands : 2 index.html:20     //legs : 2 index.html:20      //heads : 1 index.html:20     //clone : function   () {}      for (Var i in man)  {         if (Object.prototype.hasOwnProperty.call (man,i))  { //filtration              console.log (i, ":", Man[i]); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}    &nbsp}    //output is print  Hands:2,legs:2,heads:1 </script>

 

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.