【发布时间】:2014-08-13 21:22:54
【问题描述】:
我有一个包含大量分层重复的静态树,我想压缩它,在运行时将其编译成扩展形式。以这个示例对象为例:
var tree = {
root: {
"ba": "ba",
"ex": {
"aa": "aa",
"ab": "ab"
},
"ex2": {
"aa": "aa",
"ab": "ab"
}
}
};
它可以很容易地表示为:
var components = {
"#a": {
"aa": "aa",
"ab": "ab"
},
"#b": {
"ba": "ba",
"ex": "#a",
"ex2": "#a"
}
};
var tree = {
root: "#b"
};
井号表示可扩展项。我有一个扩展这个表示的编译函数:
var hashCompile = function (rootNode) {
this.compile = function (currentNode) {
if (typeof currentNode === "string" && rootNode.hasOwnProperty(currentNode))
currentNode = rootNode[currentNode];
if (typeof currentNode === "object")
for (var node in currentNode)
this.compile(currentNode[node]);
};
this.compile(rootNode);
}
hashCompile(components);
for(var branch in tree) {
if(typeof branch === "string" && components.hasOwnProperty(tree[branch]))
tree[branch] = components[tree[branch]];
}
console.log(tree);
但是,currentNode = rootNode[currentNode]; 行似乎没有发挥作用。我想知道是否有人知道我该如何解决这个问题?
【问题讨论】:
-
最初的帖子来自多个地方,我已经修改了名称以便它们可以正常工作(compileTest -> components)所以现在复制粘贴代码应该会显示实际问题。跨度>
标签: javascript recursion compilation javascript-objects compression