学习js对象和数组的递归调用,用来遍历json数据

jackxiang 2008-7-22 16:26 | |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>一个使用到for...in循环的Javascript示例</title>
</head>
<body>
<script type="text/javascript">
var data = {
    products : [ { name: "Linu", desc: "computer",    
                   price: 1000, quantity: 100, alert:null },
                 { name: "ipod", desc: "music player",
                   price:  200, quantity: 200, alert:"on sale now!" },
                 { name: "cinema display", desc: "screen",      
                   price:  800, quantity: 300, alert:"best deal!" } ],
    customer : { first: "John", last: "Public", level: "gold" }
};





  function isArray(a) {
    if(typeof a =="undefined"||null==a)
    {
      return false;
    }
    else
    {  
      return a.sort ? true : false;
    }
  }
function printObj(obj,depth,Attr)
{
  if(typeof depth=="undefined"){depth=0;}
  if(typeof Attr=="undefined"){Attr="";}
/*
  var space="";
  for(var i=0;i<=depth;i++)
  {
    space+="&nbsp;"
  }
  if(""!=Attr)
  {
    document.write(space+Attr+":<br />");
  }

  */

    if(isArray(obj))
  {
    for(var i=0;i<obj.length;i++)
    {
      printObj(obj[i],depth++,i);
    }
  }
  else{
    
    if(typeof obj=="undefined")
    {
    }else if(typeof obj=="string"||typeof obj=="number" ||typeof obj=="boolean")
    {
      
      //document.write(space+"&nbsp;"+obj+"<br />");
      document.write("&nbsp;"+obj+"<br />");
    }else
    {    
      for(var p in obj)
      {
        var eachValue=obj[p];
        printObj(eachValue,depth++,p);
      }

    }
  }

}

  printObj(data);
</script>
</body>
</html>

作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:https://jackxiang.com/post/1154/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!


最后编辑: jackxiang 编辑于2008-7-22 16:33
评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]