有没有一种通过传递字符串和值来扩展 JavaScript 对象的简单方法?
基本上我需要这样的东西:
myObject = {}
var extendObj = function(obj, path, value){
}
var path = "a.b.c", value = "ciao";
extendObj(myObject, path, value);
console.log(myObject.a.b.c) //will print "ciao"
有没有一种通过传递字符串和值来扩展 JavaScript 对象的简单方法?
基本上我需要这样的东西:
myObject = {}
var extendObj = function(obj, path, value){
}
var path = "a.b.c", value = "ciao";
extendObj(myObject, path, value);
console.log(myObject.a.b.c) //will print "ciao"
myObject = {};
var extendObj = function (obj, path, value) {
var levels = path.split("."),
i = 0;
function createLevel(child) {
var name = levels[i++];
if(typeof child[name] !== "undefined" && child[name] !== null) {
if(typeof child[name] !== "object" && typeof child[name] !== "function") {
console.warn("Rewriting " + name);
child[name] = {};
}
} else {
child[name] = {};
}
if(i == levels.length) {
child[name] = value;
} else {
createLevel(child[name]);
}
}
createLevel(obj);
return obj;
}
var path = "a.b.c",
value = "ciao";
extendObj(myObject, path, value);
console.log(myObject.a.b.c) //will print "ciao"
http://jsfiddle.net/DerekL/AKB4Q/
您可以在控制台中看到它根据path
您输入的路径创建路径。