这是动态创建节点的函数示例:
function createNode(name) {
return({name: name, children: []});
}
function addChild(node, child) {
node.children.push(child);
return node;
}
var treeData = createNode("");
var subChild = createNode("");
addChild(subChild, createNode("A31"));
addChild(treeData, subChild);
但我建议改用原型。
通过任何级别的“路径”查找任何节点:
function findNodeByPath(root, path) {
var curr;
while(root && ((curr = path.splice(0,1)[0]) !== undefined)) {
if (root.children) root = root.children[curr];
else root = undefined;
}
return root;
}
function findNodeByName(root, namePath, create) {
var curr;
while(root && ((curr = namePath.splice(0,1)[0]) !== undefined)) {
if (root.children) {
var found = undefined;
for (var i = 0; !found && i < root.children.length; i++)
if (root.children[i].name == curr) found = root.children[i];
if (create && !found) {
found = createNode(curr);
addChild(root, found);
}
root = found;
}
else root = undefined;
}
return root;
}
var A31 = findNodeByPath(treeData, [0, 0]); // Will return the node with name A31
addChild(A31, createNode("A31 child 1"));
addChild(A31, createNode("A31 child 2"));
// second child will be accessible by:
var secondChildOfA31 = findNodeByPath(treeData, [0, 0, 1]);
// also to find node by the name:
var secondChildOfA31 = findNodeByName(treeData, ["", "A31", "A31 child 2"]);
// will create all intermenient nodes with respective names:
var veryDeepChild = findNodeByName(treeData, ["foo", "bar", "baz", "quux", "moo"], true);
function createOuterNode(name, childNode) {
return {name: name, children: childNode? [childNode] : []}
}
// Example to create nodes in the question:
var CNode = createOuterNode("C");
var BNode = createOuterNode("B", CNode);
var ANode = createOuterNode("A", BNode);
// Example using LOOP:
var list = ["A", "B", "C"];
var outer = undefined;
for (var i = list.length - 1; i >= 0; i--) outer = createOuterNode(list[i], outer);
// outer will contain A node with child B with child C
console.log(outer);