简体   繁体   English

从子数组中获取父数组

[英]Get parent array from child array

In the code below I can easily enter into a subarray within the array with current = current[0] .在下面的代码中,我可以使用current = current[0]轻松进入数组中的子数组。

 var root = [ [ 'Value 1', ] ]; var current = root; current = current[0]; current.push('Value 2'); document.write(JSON.stringify(root));

How can I do the reverse and go up a level?我怎样才能做反向和 go 上一个级别? In this example, current would become:在此示例中, current将变为:

[['Value 1', 'Value 2']]

The only way I can think of doing this would be looping, but duplicates would be very probably and problematic.我能想到的唯一方法是循环,但重复很可能是有问题的。 All I've found online is looping, which won't work as a mention in the last sentence.我在网上找到的只是循环,最后一句中没有提到。

EDIT编辑

I'm looping through a large string and converting it to a tree.我正在遍历一个大字符串并将其转换为一棵树。 Certain characters will require a indent in the tree or a separate branch, while others will require an outdent and return to the parent function.某些字符需要在树中缩进或单独的分支,而其他字符则需要缩进并返回父 function。 I've achieved the indents by having a current variable just enter a new subarray as suggested here .我已经通过让current变量按照这里的建议输入一个新的子数组来实现缩进。 I just need a way to exit with a different character.我只需要一种以不同角色退出的方法。

You can't.你不能。

Arrays have no concept of a "parent" or anything. Arrays 没有“父母”或任何东西的概念。 They don't care where their references are being held.他们不在乎他们的参考资料存放在哪里。 However, if you really really need to, you can implement the concept of a "parent" yourself using a simple recursive function setting properties of the arrays - see below:但是,如果您真的需要,您可以使用 arrays 的简单递归 function 设置属性自己实现“父”的概念 - 见下文:

 var root = [ [ 'Value 1', ] ]; function setParents(root) { for(var i = 0; i < root.length; i++) { if(Array.isArray(root[i])) { root[i].parent = root; setParents(root[i]); } } } setParents(root); var current = root; current = current[0]; current.push('Value 2'); document.write(JSON.stringify(root)); current = current.parent; console.log(current);

This makes use of the fact that array properties don't show up when logged or serialized as JSON, only their elements.这利用了数组属性在记录或序列化为 JSON 时不显示的事实,仅显示它们的元素。 So they're kind of "hidden" in a sense.所以从某种意义上说,它们有点“隐藏”。 It's a bit hacky but could work for you.这有点hacky,但可以为你工作。

However, I recommend you simply avoid overwriting current - there's not really a great need to use it like a cursor traversing some hierarchy structure.但是,我建议您简单地避免覆盖current - 并没有真正需要像 cursor 遍历某些层次结构那样使用它。

Simply pushing BEFORE setting current variable will work.只需在设置当前变量之前按下即可。

 var root = [ [ 'Value 1', ] ]; var current = root; root.push("AAA"); current = current[0]; current.push('Value 2'); document.write(JSON.stringify(root));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM