Packing tree into array in Javascript
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 = [];
}
精彩评论