如何通过字符串路径修改变量而非仅实现变量访问功能
嵌套属性更新实现方案
你现有变量访问函数存在逻辑错误:return 语句被放在了for循环内部,只会处理第一个命名空间片段就返回,无法适配多层级嵌套路径的访问需求,先修正访问逻辑再实现更新能力。
实现思路
要更新嵌套属性,不能直接返回最终属性值,需要先定位到最终属性的父级对象和对应的属性名,再通过父级对象完成赋值操作即可。
完整代码实现
// 修正后的嵌套属性访问函数 function accessVariable(accessPath, rootObj) { const namespaces = accessPath.split(".").filter(Boolean); let current = rootObj; for (let i = 0; i < namespaces.length; i++) { try { current = current[namespaces[i]]; } catch { return undefined; } if (current === undefined || current === null) break; } return current; } // 新增嵌套属性更新函数 function updateVariable(accessPath, rootObj, newValue) { const namespaces = accessPath.split(".").filter(Boolean); // 处理仅一级属性的场景 if (namespaces.length === 1) { rootObj[namespaces[0]] = newValue; return true; } // 遍历到最终属性的父级对象 let parent = rootObj; for (let i = 0; i < namespaces.length - 1; i++) { try { parent = parent[namespaces[i]]; } catch { return false; } if (parent === undefined || parent === null) return false; } // 对最终属性赋值 const finalKey = namespaces[namespaces.length - 1]; parent[finalKey] = newValue; return true; }
使用示例
const demo = { a: { b: { c: 10 } } }; // 访问属性 console.log(accessVariable("a.b.c", demo)); // 输出 10 // 更新属性 updateVariable("a.b.c", demo, 20); console.log(demo.a.b.c); // 输出 20
说明
如果路径中间层级不存在,更新函数会返回false表示更新失败,你可以根据业务需要调整逻辑,自动创建不存在的中间层级。
内容的提问来源于stack exchange,提问作者bright gao
相关产品推荐
相关产品推荐

