1. /*
    2. 树的操作:添加、删除、查找、修改
    3. 树节点数据 - 父子
    4. */
    5. class Tree{
    6. constructor(value) {
    7. this.root = new TreeNode(value);
    8. }
    9. getRoot() {
    10. return this.root;
    11. }
    12. getById(id) {
    13. function find(node) {
    14. if(node.id === id) {
    15. return node;
    16. } else {
    17. for(let i = 0; i < node.childNode.length; i++) {
    18. let res = find(node.childNode[i]);
    19. if(res) return res;
    20. }
    21. }
    22. }
    23. return find(this.root)
    24. }
    25. }
    26. class TreeNode{
    27. constructor(value) {
    28. this.value = value;
    29. this.parentNode = null;
    30. this.childNode = [];
    31. this.id = undefined;
    32. }
    33. // 添加子节点
    34. appendChild(node) {
    35. this.childNode.push(node);
    36. node.parentNode = this;
    37. }
    38. // 删掉某个子节点
    39. removeChild(node) {
    40. // 先按照最底层的写法实现
    41. for(let i = 0; i < this.childNode.length; i++){
    42. if(this.childNode[i] === node) {
    43. this.childNode.splice(i, 1);
    44. node.parentNode = undefined;
    45. return ;
    46. }
    47. }
    48. }
    49. // 查找节点
    50. }
    51. const tree = new Tree('html');
    52. const root = tree.getRoot();
    53. const header = new TreeNode('header');
    54. const body = new TreeNode('body');
    55. const p = new TreeNode('p');
    56. p.id = 'p1'
    57. root.appendChild(header);
    58. root.appendChild(body);
    59. body.appendChild(p);
    60. console.log(tree.getById('p1'));
    61. console.log(root);

    总结:
    image.png