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

Javascript链接对象:如何将元素添加到链的末尾?,javascript,Javascript,考虑下面的链接对象和给定代码: let data = { item: "0001", child: { item: "00011", child: { item: "000111", child: { item: "0001111", child: { item: "00011111",

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

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

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

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

let数据={
项目:“0001”,
儿童:{
项目:“00011”,
儿童:{
项目:“000111”,
儿童:{
项目:“000111”,
儿童:{
项目:“0001111”,
子项:空
}
}
}
}
};
让last=data;//从数据开始
while(last.child!==null){//检查子项
last=last.child;//为检查孩子的孩子而分配孩子
}
last.child={item:“9999”,child:null};//将新对象指定给的属性
//保留参考资料
console.log(数据);//相同的原始数据。完全没有效果

.as console wrapper{max height:100%!important;top:0;}
您在此处创建了一个新对象,而不是在变量
last
中编辑当前对象:

last = {
    item: "9999",
    child: null
};
如果要更改属性,需要使用
表示法,如

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

你可能想用另一种方式:

while (last.child !== null) last = last.child;
这将对您进行设置,以便
last.child
null
,并且您将能够使用
last.child={item:“9999”,child:null}正确分配

由于希望将
last
保留为引用指针,因此不希望将其重新指定给新对象。这样,您可以导航到最后一个子对象,并将其子对象指定给您的对象。

您可以使用递归:

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

解释得很好。谢谢