我有一个静态树,其中包含大量分层重复,并且想要对其进行压缩,在运行时将其编译为其扩展形式。以这个示例对象为例:
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];
行似乎没有完成其工作。我想知道是否有人知道如何解决这个问题?
最佳答案
function test(value) {
value = value + 1; // X
console.log(value);
}
var a = 1;
test(a); // 2
console.log(a); // 1
var b = {inner: 1};
test(b.inner); // 2
console.log(b.inner); // 1
对参数的赋值不会将其传播到调用站点中的 L 值。
您可以尝试让该函数返回一个值。
function test2(value) {
return value + 1;
}
var a = 1;
a = test2(a);
var b = {inner: 1};
b.inner = test2(b.inner);
关于Javascript对象编译算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25296376/