简体   繁体   English

在JavaScript中创建树状结构

[英]Create tree like structure in javascript

How can I have a reference to an object in javascript? 如何在javascript中引用对象? I have the following code: 我有以下代码:

// 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);

I know that if I create NodeB before creating NodeA it will solve my problem. 我知道,如果在创建NodeA之前先创建NodeB,它将解决我的问题。

You can use Object.assign to assign properties to NodeB instead of setting NodeB to be a reference to a entirely new object: 您可以使用Object.assignNodeB分配属性,而不是将NodeB设置为对全新对象的引用:

 var NodeB = {}; var NodeA = { name: "A", children: [ NodeB ] } Object.assign( NodeB, { name: "B", children: [] } ); var test = NodeA.children[0].name; alert(test); 

Note that for Internet Explorer of Object.assign support you would need to use the Polyfill . 请注意,要获得Object.assign Internet Explorer支持,您需要使用Polyfill You could also just assign the properties to the existing object instead of using object literal notation to create a new one: 您也可以只将属性分配给现有对象,而不是使用对象文字符号来创建一个新的属性:

 var NodeB = {}; var NodeA = { name: "A", children: [ NodeB ] } NodeB.name = "B"; NodeB.children = []; var test = NodeA.children[0].name; alert(test); 

Why not use a function constructor: 为什么不使用函数构造函数:

 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>'); 

When you assign a new value you are removing the reference of the object and then you cannot access to the object that inside children array 分配新值时,您将删除对象的引用,然后您将无法访问children数组内的对象

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

You can use dot notation to assign a new properties: 您可以使用dot符号来分配新属性:

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

Example: 例:

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM