javascript - 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 中添加新项目?
解决方案
您需要检查下一个子元素,因为您需要一个子属性来分配对象。
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; }
推荐阅读
- php - 在 WooCommerce 产品中显示自定义帖子类型的类别
- reactjs - React:如何将启动文件 index.html 更改为 manifest.json 的 start_url 中的其他 html 页面
- c - 调用外部程序,在运行时下载并在裸机上获取返回数据
- assembly - 寄存器 AL 和 AX 溢出到哪里?
- python - SMOTENC:无法将字符串转换为浮点数
- ios - iOS HERE SDK NMAKit 私有 API 使用
- maven - 无论如何要在 github 操作工作流中签署 maven 包吗?
- excel - 使用 VBA 和 IBM Lotus Notes 发送电子邮件
- regex - 正则表达式 (0*1*)* 和 (0 + 1)* 是否相同?
- splunk - 从请求正文 splunk 中提取所有出现的相同字段