课程: JavaScript: Five Advanced Challenges and Concepts

免费学习该课程!

今天就开通帐号,24,700 门业界名师课程任您挑!

Creating a recursive function to generate a nested array

Creating a recursive function to generate a nested array - JavaScript教程

课程: JavaScript: Five Advanced Challenges and Concepts

Creating a recursive function to generate a nested array

- [Instructor] With a nested array in hand, we are faced with our next challenge. How do you output data from a nested array without having to create a convoluted function of if else statements and endless nesting of its own? Because now that we have this nested array, we'd have to go and say, if the current item has a parent of zero, then output it here. Otherwise, if it has a parent of anything else, then find a parent. Then change the HTML output to match that this is now a child instead of a parent, and then output the content inside the child, and then go back out again unless there's another child. In which case, you see how this gets really convoluted? Well, fortunately, there's a way of getting around this problem by creating a recursive function, a function that calls itself. Now recursive functions are not to be trifled with because they can easily lead to endless loops. The good news is that's relatively easy…

内容