在 Javascript 中将树打包到数组中

发布于 2024-08-21 20:20:01 字数 632 浏览 6 评论 0原文

好吧,所以这应该不难,但是我遇到了奇怪的和奇怪的侥幸。

我试图将一棵树打包到一个数组中,其中每个节点类似于:

  • 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不回头走下去 2024-08-28 20:20:01

您使用 undefined 值的方式与 Javascript 标准实践不一致。我不确定这是否能解决您的问题,但尝试将代码更改为

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

“这可能确实有帮助”。另外,正如您所看到的,使用数组构造函数是不必要的:[] 创建一个新的空数组。

Undefined 并不是 Javascript 中实际的保留字。没有什么可以阻止您进行设置

undefined = 2;

,之后与它的任何比较都会出现不可预测的行为。

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.

苍白女子 2024-08-28 20:20:01

您尝试过 in 运算符吗?

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

Have you tried the in operator?

if (!("children" in node))
  node.children = [];
断舍离 2024-08-28 20:20:01

要检查对象上是否存在属性,请使用 hasOwnProperty

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

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

if (!node.hasOwnProperty('children')) {
    node.children = [];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文