This article shows you the differences between js traversal of arrays and traversing objects. in general, for is used to traverse array objects while for-in is used to traverse non-array objects. Next, let's make up the differences between js traversal arrays and objects, as well as a detailed explanation of js recursive traversal objects, arrays, and attributes. Let's take a look at it and let's not talk much about it. Let's go straight to the theme. You, the Code is as follows:
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 non-array objects var man = {hands: 2, legs: 2, heads: 1}; // Add the clone method for all objects, that is, add the prototype attribute to the built-in prototype (object, Array, function). This method is very powerful, it is also dangerous if (typeof Object. prototype. clone = "undefined") {Object. prototype. clone = function () {};}// for (var I in man) {if (man. hasOwnProperty (I) {// filter, only the private property console of man is output. log (I, ":", man [I]) ;}/// the output result is print hands: 2, legs: 2, heads: 1 for (var I in man) {// do not use the filter console. log (I, ":", man [I]);} // The output result 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 the console. log (I, ":", man [I]) ;}// the output result is print hands: 2, legs: 2, heads: 1 script
Next, we will introduce js recursive traversal objects, arrays, and attributes.
When working on the front-end, we sometimes need to traverse some unknown objects. 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]); // The value is displayed.
}
}
}
// Traverse all Ur values in the object
Function TraversalObject (obj)
{
For (var a in obj ){
If (a = "Url") alert (obj [a]); // display the URL Value
If (typeof (obj [a]) = "object "){
TraversalObject (obj [a]); // recursive Traversal
}
}
}
This Traversal method plays a very good role when the object is irregular but needs to obtain the same attribute.
For more details about the differences between JS traversal arrays and objects and the methods for Recursive traversal of objects, arrays, and attributes, please follow the PHP Chinese website!