在 Javascript 中将树打包到数组中
好吧,所以这应该不难,但是我遇到了奇怪的和奇怪的侥幸。
我试图将一棵树打包到一个数组中,其中每个节点类似于:
- title: string-for-display
- key: id-value
- Children: 子节点数组
这个侥幸太奇怪了,我根本无法理解它:当我尝试向节点添加子节点时,我做了类似的事情,
if(node.children == undefined) {
node.children = new Array();
}
node.children.push({ title: value, key: key });
即删除一些先前插入的节点......所以我做了一些调试,发现这段代码:
if(node.children == undefined) {
node.children = new Array();
}
有错误,这根本没有任何意义- 如果node.children未定义,node.children = new Array()不应该删除任何东西......,对吗?
我做错了什么吗?如果是这样,我如何将树打包到 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: 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用
undefined
值的方式与 Javascript 标准实践不一致。我不确定这是否能解决您的问题,但尝试将代码更改为“这可能确实有帮助”。另外,正如您所看到的,使用数组构造函数是不必要的:
[]
创建一个新的空数组。Undefined 并不是 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 toThis 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
after which any comparisons to it will behave unpredictably.
您尝试过
in
运算符吗?Have you tried the
in
operator?要检查对象上是否存在属性,请使用
hasOwnProperty
To check if a property exists on an object, use
hasOwnProperty