标签:
数组如下:
var item=[{ name:‘Tom‘, age:70, child:[{ name:‘Jerry‘, age:50, child:[{ name:‘William‘, age:20 }] }, { name:‘Jessi‘, age:30 }]
}];
输出的HTTML如下:
1 <ol> 2 <li>name:Tom</li> 3 <li>age:70</li> 4 <li>children: 5 <ol> 6 <li>name:Jerry</li> 7 <li>age:50</li> 8 <li>children: 9 <ol> 10 <li>name:William</li> 11 <li>age:20</li> 12 </ol> 13 </li> 14 </ol> 15 <ol> 16 <li>name:Jessi</li> 17 <li>age:30</li> 18 </ol> 19 </li> 20 </ol>
思路分析:该数组是嵌套数组,遍历数组,当前元素具有child时,递归调用函数,不具有child时,</ol>结尾后封闭网页元素。
JavaScript函数实现如下:
1 var str=""; 2 function test(obj){ 3 for(var key in obj){ 4 str+="<ol>"; 5 if(obj[key].hasOwnProperty("name")){ 6 str=str+"<li>"+"name:"+obj[key].name+"</li>"; 7 } 8 if (obj[key].hasOwnProperty("age")) { 9 str=str+"<li>"+"age:"+obj[key].age+"</li>"; 10 } 11 if(!obj[key].hasOwnProperty("child")){ 12 str+="</ol>"; 13 str+="</li>"; 14 str+="</ol>"; 15 } 16 if(obj[key].hasOwnProperty("child")){ 17 str=str+"<li>"+"children:"; 18 test(obj[key].child); 19 } 20 } 21 } 22 test(item); 23 console.log("%s",str);
前端笔试题目总结——应用JavaScript函数递归打印数组到HTML页面上
标签:
原文地址:http://www.cnblogs.com/meggie523/p/4824575.html