【问题标题】:Javascript object compilation algorithmJavascript对象编译算法
【发布时间】: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


【解决方案1】:
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);

【讨论】:

    【解决方案2】:

    部分由于客人的观察,我改变了我的算法:

    var hashCompile = function (rootNode) {
        this.compile = function (currentNode) {
            for(node in currentNode) {
                if(typeof currentNode[node] === "string" && rootNode.hasOwnProperty(currentNode[node])) {
                    currentNode[node] = rootNode[currentNode[node]];
                    compile(currentNode[node]);
                }
                else if(typeof currentNode === "object")
                    compile(currentNode[node]);
            }
        };
        this.compile(rootNode);
    };
    

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 2015-05-08
      • 2019-04-20
      • 1970-01-01
      • 2018-05-19
      • 2020-06-12
      • 2011-04-23
      • 1970-01-01
      • 2011-01-09
      相关资源
      最近更新 更多