递归一般是在函数里面把函数自己给调用一遍,通过每次调用改变条件,来结束循环。

    1. var data = [
    2. {
    3. name: "所有物品",
    4. children: [
    5. {
    6. name: "水果",
    7. children: [{name: "苹果", children: [{name: '青苹果'}, {name: '红苹果'}]}]
    8. },
    9. {
    10. name: '主食',
    11. children: [
    12. {name: "米饭", children: [{name: '北方米饭'}, {name: '南方米饭'}]}
    13. ]
    14. },
    15. {
    16. name: '生活用品',
    17. children: [
    18. {name: "电脑类", children: [{name: '联想电脑'}, {name: '苹果电脑'}]},
    19. {name: "工具类", children: [{name: "锄头"}, {name: "锤子"}]},
    20. {name: "生活用品", children: [{name: "洗发水"}, {name: "沐浴露"}]}
    21. ]
    22. }
    23. ]
    24. }]
    25. //递归输出所有内容
    26. var recursiveFunction = function(){
    27. var str = ''
    28. const getStr = function(list){
    29. list.forEach(function(row){
    30. if(row.children){
    31. getStr(row.children)
    32. }else {
    33. str += row.name + ";"
    34. }
    35. })
    36. }
    37. getStr(data)
    38. console.log(str)
    39. }//青苹果;红苹果;北方米饭;南方米饭;联想电脑;苹果电脑;锄头;锤子;洗发水;沐浴露;