Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the difference between JS traversal of arrays and objects and methods of recursively traversing objects, arrays, and properties

高洛峰
Release: 2017-01-14 11:09:21
Original
2930 people have browsed it

No more nonsense, let’s go straight to the topic, you, the specific code is as follows:

<script>
 //----------------for用来遍历数组对象--
 var i,myArr = [1,2,3];
 for (var i = 0; i < myArr.length; i++) {
  console.log(i+":"+myArr[i]);
 };
 //---------for-in 用来遍历非数组对象
 var man ={hands:2,legs:2,heads:1};
 //为所有的对象添加clone方法,即给内置原型(object,Array,function)增加原型属性,该方法很强大,也很危险
 if(typeof Object.prototype.clone ==="undefined"){
  Object.prototype.clone = function(){}; 
 }
 //
 for(var i in man){
  if (man.hasOwnProperty(i)) { //filter,只输出man的私有属性
   console.log(i,":",man[i]);
  };
 }
 //输出结果为print hands:2,legs:2,heads:1
 for(var i in man) {//不使用过滤
  console.log(i,":",man[i]);
 } 
 //输出结果为
 //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)) { //过滤
   console.log(i,":",man[i]);
  }
 } //输出结果为print hands:2,legs:2,heads:1 </script>
Copy after login

Next, I will introduce to you js recursive traversal of objects, arrays, and properties

Working on the front end Sometimes we need to traverse some unknown types of 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
                }
                                                      using using using using ’ ‐ ‐ ‐ ‐ ‐ ‐ ‐ traversalObject(obj[a]); //Recursive traversal Just display
    }
  }
}

//Traverse the values ​​​​of all Urs in the object

function TraversalObject(obj)
{
  for (var a in obj ) {

if(a=="Url") alert(obj[a]);//Display the value of the URL

if (typeof (obj[a]) == "object") {
            TraversalObject(obj[a]); // Recursive traversal
                                          
                                                                   Good effect.

For more detailed explanations of the differences between JS traversing arrays and objects and methods of recursively traversing objects, arrays, and properties, please pay attention to the PHP Chinese website for related articles!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!