如何通过字符串“path.to.obj”访问
我遇到问题的原因是你需要跳过最后一个路径。如果包括最后一个路径,你最终只会分配一个任意对象。
myobject[path][to][obj]
?我想调用一个函数Settings.write('path.to.setting', 'settingValue')
,它将'settingValue'
写入settingObj[path][to][setting]
。我如何在不使用eval()
的情况下实现这一点?我最终在与下面的一个用户回答它的同时弄清了这个问题。如果有人感兴趣,我会在此处发布我的文档以说明它的工作原理。(function(){
var o = {}, c = window.Configure = {};
c.write = function(p, d)
{
// Split the path to an array and assaign the object
// to a local variable
var ps = p.split('.'), co = o;
// Iterate over the paths, skipping the last one
for(var i = 0; i < ps.length - 1; i++)
{
// Grab the next path's value, creating an empty
// object if it does not exist
co = (co[ps[i]])? co[ps[i]] : co[ps[i]] = {};
}
// Assign the value to the object's last path
co[ps[ps.length - 1]] = d;
}
c.read = function(p)
{
var ps = p.split('.'), co = o;
for(var i = 0; i < ps.length; i++)
{
co = (co[ps[i]])? co[ps[i]] : co[ps[i]] = {};
}
return co;
}
})();
我遇到问题的原因是你需要跳过最后一个路径。如果包括最后一个路径,你最终只会分配一个任意对象。
co = (co[ps[i]])? co[ps[i]] : co[ps[i]] = {};
。 - LordZardeck