开发者

Packing tree into array in Javascript

开发者 https://www.devze.com 2022-12-20 11:04 出处:网络
Ok, so this shouldn\'t be difficult, however I have encountered weird and bizarra flukes. I am trying to pack a tree into an array, where each node is something like:

Ok, so this shouldn't be difficult, however I have encountered weird and bizarra flukes.

I am trying to pack a tree into an array, where each node is something like:

  • title: string-for-display
  • key: id-value
  • children: array of child nodes

the fluke is so strange I can't comprehend it at all: when I try to add a child to a node, I do something like

if(node.children == undefined) {
  node.children = new Array();
}

node.children.push({ title: value, key: k开发者_Python百科ey });

this was deleting some previously inserted nodes....so I did some debugging and found that this code:

if(node.children == undefined) {
  node.children = new Array();
}

was at fault, which doesn't make any sense at all - node.children = new Array() shouldn't delete ANYTHING if node.children is undefined......, right?

Am I doing something wrong? if so, how do I pack the tree into an array in Javascript?


The way you are using the undefined value is not consistent with Javascript standard practices. I'm not sure if this will solve your problem, but try changing you code to

if (typeof(node.children) == 'undefined') { 
  node.children = [];
}

This might actually help. Also, as you can see, using the Array constructor is unnecessary: [] creates a new empty array.

Undefined is not an actual reserved word in Javascript. There is nothing preventing you from setting

undefined = 2;

after which any comparisons to it will behave unpredictably.


Have you tried the in operator?

if (!("children" in node))
  node.children = [];


To check if a property exists on an object, use hasOwnProperty

if (!node.hasOwnProperty('children')) {
    node.children = [];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消