Differences between JS traversing arrays and objects and details of how to recursively traverse objects arrays and attributes

  • 2021-06-28 10:37:57
  • OfStack

Say nothing more, go straight to the topic, you, the code is as follows:


<script>
 //----------------for Used to traverse array objects --
 var i,myArr = [1,2,3];
 for (var i = 0; i < myArr.length; i++) {
  console.log(i+":"+myArr[i]);
 };
 //---------for-in  Used to traverse non-array objects 
 var man ={hands:2,legs:2,heads:1};
 // Add for all objects clone Method, i.e. giving built-in prototypes (object,Array,function) Add Prototype Properties , This method 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 man Private property of 
   console.log(i,":",man[i]);
  };
 }
 // The output is print hands:2,legs:2,heads:1
 for(var i in man) {// Do not use filtering 
  console.log(i,":",man[i]);
 } 
 // The 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)) { // filter 
   console.log(i,":",man[i]);
  }
 } // The output is print hands:2,legs:2,heads:1 </script>

Next, we introduce js recursive traversal of objects, arrays, attributes

When working on the front end, sometimes we need to traverse an object of unknown type.The code is as follows:

//js traversal object
function TraversalObject(obj)
{
for (var a in obj) {
if (typeof (obj[a]) == "object") {
TraversalObject (obj [a]); //Recursive traversal
}
else {
alert (a +'='+ obj [a]);//Value is displayed
}
}
}

//Traverse all Ur values in the object
function TraversalObject(obj)
{
for (var a in obj) {

if (a=="Url") alert (obj[a]); / /Show the value of URL
if (typeof (obj[a]) == "object") {
TraversalObject (obj [a]); //Recursive traversal
}
}
}

This traversal method works well when objects are irregular but need to acquire the same attributes.


Related articles: