2

有没有一种通过传递字符串和值来扩展 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"
4

1 回答 1

3
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您输入的路径创建路径。

于 2013-04-24T02:07:58.413 回答