【发布时间】:2012-02-18 03:14:34
【问题描述】:
如何通过字符串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;
}
})();
我遇到问题的原因是您必须跳过最后一条路径。如果你包含最后一条路径,你最终只会分配一个任意对象。
【问题讨论】:
标签: javascript