代码之家  ›  专栏  ›  技术社区  ›  Mendes

javascript链接对象:如何将元素添加到链的末尾?

  •  2
  • Mendes  · 技术社区  · 6 年前

    考虑下面的链接对象和给定的代码:

    let data = {
        item: "0001",
        child: {
            item: "00011",
            child: {
                item: "000111",
                child: {
                    item: "0001111",
                    child: {
                        item: "00011111",
                        child: null
                    }
                }
            }
        }
    };
    
    // Add item to last child of data
    let last = data.child;
    while (last !== null) last = chain.child;
    
    // Add this item as last in chain
    last = {
        item: "9999",
        child: null
    };
    
    console.log(data); // Same original data. No effect at all!!!
    

    如何在最后一个子对象中添加新项?

    4 回复  |  直到 6 年前
        1
  •  2
  •   Nina Scholz    6 年前

    let data = {
        item: "0001",
        child: {
            item: "00011",
            child: {
                item: "000111",
                child: {
                    item: "0001111",
                    child: {
                        item: "00011111",
                        child: null
                    }
                }
            }
        }
    };
    
    let last = data;                            // start with data
    while (last.child !== null) {               // check the child
        last = last.child;                      // assig child for check of the child's child
    }
    
    last.child = { item: "9999", child: null }; // assign new object to a property for
                                                // keeping the reference
    
    console.log(data); // Same original data. No effect at all!!!
    .as-console-wrapper { max-height: 100% !important; top: 0; }
        2
  •  2
  •   Sunny Patel    6 年前

    while (last.child !== null) last = last.child;
    

    last.child null last.child = {item: "9999", child: null};

    last

        3
  •  0
  •   Sebastian Speitel    6 年前

    last

    last = {
        item: "9999",
        child: null
    };
    

    .

    last.child = {item:"9999",child:null};
    
        4
  •  0
  •   enno.void    6 年前

    let data = {
        item: "0001",
        child: {
            item: "00011",
            child: {
                item: "000111",
                child: {
                    item: "0001111",
                    child: {
                        item: "00011111",
                        child: null
                    }
                }
            }
        }
    };
    
    let run = function(node, addNode){
    if(node.child === null){
        node.child = addNode
        return;
    }
    
    return run(node.child, addNode)
    }
    
    last = {
        item: "9999",
        child: null
    };
    run(data, last)
    console.log(data); 
    

    https://jsfiddle.net/q89vt6mn/3/