You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 while loop 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 original current object instead of the newly created children property. This overwrites the same children property each time instead of building a nested chain.
  • Misordered Depth Check: You create the children property before checking the depth, which would add an extra (unwanted) children even when depth reaches 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 depth hits 0 or lower, we exit the function to stop further nesting.
  • Nested Chain Creation: For each recursive call, we create a children property on the current object, then immediately recurse on that new children object with depth-1. This builds the exact chain parent.children.children.children.children when depth=4.

Test Output

If you run the code above, parent will look like this:

{
  children: {
    children: {
      children: {
        children: {}
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者uniXVanXcel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:46:04