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: key });
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?
-
This seems entirely unrelated to the problem of storing a tree structure in an array.Anon.– Anon.2010年02月16日 00:18:39 +00:00Commented Feb 16, 2010 at 0:18
3 Answers 3
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.
1 Comment
Have you tried the in operator?
if (!("children" in node))
node.children = [];
Comments
To check if a property exists on an object, use hasOwnProperty
if (!node.hasOwnProperty('children')) {
node.children = [];
}
Comments
Explore related questions
See similar questions with these tags.