JavaScript递归函数实现多重映射数据转树对象失败排查求助
Let's break down what's going wrong with your recursive function and fix it step by step:
Key Issues in Your Code
1. forEach callbacks ignore return values
The return statement inside your forEach callback doesn’t do what you think it does. forEach runs its callback for every element, and any return inside that callback only exits the current callback iteration—it doesn’t return a value to the parent recurse function, nor does it stop the loop.
When your node has children (e.g., c or f), the recurse function finishes processing the forEach loop but doesn’t have an explicit return statement afterward. That means it defaults to returning undefined, which is why you’re seeing that unexpected value.
2. Undeclared variables cause silent bugs
You’re using newNode and newChildnode without declaring them with let or const. This puts them in the global scope, which can lead to unexpected overwrites if your tree has multiple nodes with similar names. Always declare your variables to avoid this.
3. Missing return for nodes with children
Even if the forEach worked the way you expected, you need to return the current node after attaching all its children. Right now, only leaf nodes hit the else block and return a value—parent nodes don’t, leading to undefined.
Fixed Code
Here’s the corrected version of your code with explanations:
// Define your multimap (keep your existing definition here) const myMultiMap = ...; // Initialize tree with root node 'aaaa' (fixed the typo from 'End2End' to match your desired structure) const myTree = new Tree('aaaa'); // Build child nodes starting from 'aaaa' myMultiMap.get('aaaa').forEach((entry) => { const newNode = new Tree(entry); // Declare variable with const myTree.appendChildNode(recurse(newNode)); }); // Print the final tree myTree.print(); // Fixed recursive function function recurse(node) { // Check if current node has children in the multimap if (myMultiMap.has(node.name)) { myMultiMap.get(node.name).forEach((child) => { const newChildNode = new Tree(child); // Declare variable with const // No need to return here—we just need to attach the recursive child node.appendChildNode(recurse(newChildNode)); }); } // Always return the current node, whether it has children or not return node; }
Why This Works
- No more
undefinedreturns: Therecursefunction now always returns thenodeobject, whether it’s a leaf or a parent with children. This ensuresappendChildNodereceives a valid Tree instance every time. - Proper variable scoping: Using
constfor all new node variables prevents global scope leaks and accidental overwrites. forEachused correctly: We’re usingforEachpurely for iteration to attach children—no reliance on its callback to return values, which isn’t its intended purpose.
When you run this corrected code, your print() method should output exactly the tree structure you wanted:
aaaa ├─ b ├─ c │ └─ f │ └─ g └─ d
内容的提问来源于stack exchange,提问作者A.T.

