在javascript中创建树状结构

时间:2016-04-28 17:46:32

标签: javascript oop

如何在javascript中引用对象?我有以下代码:

// define nodes
var NodeA = new Object();
var NodeB = new Object();

NodeA = {
    name: "A",
    children: [
        NodeB
    ]
}

NodeB = {
    name: "B",
    children: []
};

var test = NodeA.children[0].name;
// How can I make test = "A" ???  <----------------
alert(test);

我知道如果我在创建NodeA之前创建NodeB,它将解决我的问题。

3 个答案:

答案 0 :(得分:4)

您可以使用Object.assign将属性分配给NodeB,而不是将NodeB设置为对全新对象的引用:

&#13;
&#13;
var NodeB = {};

var NodeA = {
    name: "A",
    children: [
        NodeB
    ]
}

Object.assign( NodeB, {
    name: "B",
    children: []
} );

var test = NodeA.children[0].name;
alert(test);
&#13;
&#13;
&#13;

请注意,对于Object.assign支持的Internet Explorer,您需要使用Polyfill。 您也可以将属性分配给现有对象,而不是使用对象文字表示法来创建新对象:

&#13;
&#13;
var NodeB = {};

var NodeA = {
    name: "A",
    children: [
        NodeB
    ]
}

NodeB.name = "B";
NodeB.children = [];

var test = NodeA.children[0].name;
alert(test);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

为什么不使用函数构造函数:

&#13;
&#13;
function Node(name) {
    this.name = name,
    this.children = [];
}

var nodeA = new Node('A'),
    nodeB = new Node('B');

nodeA.children.push(nodeB);

document.write(nodeA.children[0].name);
document.write('<pre>' + JSON.stringify(nodeA, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 2 :(得分:0)

分配新值时,您将删除对象的引用,然后无法访问children数组

内的对象
NodeB = {
    name: "B",
    children: []
};

您可以使用dot表示法分配新属性:

NodeB.name = "B";
NodeB.children = [];

示例:

&#13;
&#13;
var NodeA = new Object();
var NodeB = new Object();

NodeA = {
    name: "A",
    children: [
        NodeB
    ]
}

NodeB.name = "B";
NodeB.children = [];

var test = NodeA.children[0].name;

alert(test);
&#13;
&#13;
&#13;