首页 > 解决方案 > Javascript链式对象:如何将元素添加到链的末尾?

问题描述

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

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!!!

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

标签: javascript

解决方案


您需要检查下一个子元素,因为您需要一个子属性来分配对象。

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; }


推荐阅读