【问题标题】:JavaScript -TypeError: Cannot read property 'children' of undefinedJavaScript -TypeError:无法读取未定义的属性“孩子”
【发布时间】:2019-01-29 18:49:25
【问题描述】:

我正在尝试创建一棵树并计算它的高度。 map 数组在 for 循环中正确初始化,但 console.log(map+" this is map"); 显示 [object Object],[object Object],[object Object],[object Object],[object Object] this is map。我在

的第二个 for 循环中访问 c​​hildren 属性时遇到问题
map[list[i]]["children"].push(node);

错误是TypeError: Cannot read property 'children' of undefined 这个怎么解决??

输入是 -

5
4 -1 4 1 1

第一行包含节点数????。第二行包含 ????整数 从 -1 到 ???? − 1 — 节点的父节点。如果其中第 ????-th 个 (0 ≤ ?????? ≤ ???? - 1) 为 -1,则节点 ????是根, 否则它是 ????-th 节点的父节点的从 0 开始的索引。保证只有一个根。 保证输入代表一棵树。

代码-

var readline = require('readline');

var input = [];
enter image description here
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.prompt();

rl.on('line', function (cmd) {
    input.push(cmd);
});

rl.on('close', function (cmd) {
   input=input[1].split(" ");
    console.log(list_to_tree(input));
    let tree1=list_to_tree(input);
    console.log("this   "+height(tree1));
    process.exit(0);
});


function list_to_tree(list) {
    var map = [], node, roots = [], i;
    for(i=0;i<list.length;i++){
        map.push({[i] :list[i],
            children:[]
        });
        console.log(map);

    } 
    console.log(map+"  this is map");
    for(i=0;i<list.length;i++){
        node=map[i];
        if(list[i]!==-1){
            console.log(map[list[i]]);
            map[list[i]]["children"].push(node);

        }
        else {
            roots.push(node);}
    }
    return roots;
}


function height(tree){
    if(tree===null){return 0;}

   let h=0;
    for(let x in tree){
        for (let y in tree[x]["children"]){
            h=Math.max(h,height(y));

        }
         return h+1;
    }



}

【问题讨论】:

标签: javascript node.js data-structures tree


【解决方案1】:

将“地图”声明为对象数组。然后像这样使用。

map.push({node})

我遇到了同样的问题,我确实喜欢这个。声明为对象数组的列表。

【讨论】:

  • 这会起作用,但我将如何访问 children 属性以将子节点添加到节点。 map.push({node}) 只是将一个节点推送到地图中,但我想将该节点作为子节点添加到另一个节点。我在你的提示中遗漏了什么吗??
猜你喜欢
  • 2019-02-19
  • 1970-01-01
  • 2017-06-29
  • 2019-03-06
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多