假设我们只有
var obj = {}; var propName = "foo.bar.foobar";
我们如何将属性obj.foo.bar.foobar设置为某个值(例如“ hello world”)?所以我想实现这一点,尽管我们只有字符串中的属性名称:
obj.foo.bar.foobar
obj.foo.bar.foobar = "hello world";
function assign(obj, prop, value) { if (typeof prop === "string") prop = prop.split("."); if (prop.length > 1) { var e = prop.shift(); assign(obj[e] = Object.prototype.toString.call(obj[e]) === "[object Object]" ? obj[e] : {}, prop, value); } else obj[prop[0]] = value; } var obj = {}, propName = "foo.bar.foobar"; assign(obj, propName, "Value");