如何在JavaScript中递归创建指定深度的子属性?
Fixing Your Recursive Nested Children Function
Let's break down the issues in your current code and fix it to create the nested structure you need.
Problems in Your Current Code
- Unnecessary While Loop: You're using a
whileloop inside a recursive function, but you return immediately in the first iteration—so the loop never actually repeats anything. Recursion itself is meant to handle repeated nested creation, making the loop redundant. - Incorrect Recursive Target: When you call
makechildren(current, depth-1), you pass the originalcurrentobject instead of the newly createdchildrenproperty. This overwrites the samechildrenproperty each time instead of building a nested chain. - Misordered Depth Check: You create the
childrenproperty before checking the depth, which would add an extra (unwanted)childreneven whendepthreaches 0.
Corrected Code
Here's the fixed version that builds the proper nested structure:
let parent = {}; function makeChildren(current, depth) { // Base case: stop recursion when depth is 0 if (depth <= 0) return; // Create a new children object on the current node current.children = {}; // Recurse on the new children object, decrementing depth makeChildren(current.children, depth - 1); } // Test with depth 4 makeChildren(parent, 4); console.log(parent);
How It Works
- Base Case: When
depthhits 0 or lower, we exit the function to stop further nesting. - Nested Chain Creation: For each recursive call, we create a
childrenproperty on the current object, then immediately recurse on that newchildrenobject withdepth-1. This builds the exact chainparent.children.children.children.childrenwhendepth=4.
Test Output
If you run the code above, parent will look like this:
{ children: { children: { children: { children: {} } } } }
内容的提问来源于stack exchange,提问作者uniXVanXcel
相关产品推荐
相关产品推荐

