javascript从字符串动态创建多维数组
<span id="local->ethernet->port3->rx_flow">q4234</span>
<span id="local->ethernet->port3->rx">q345</span>
<span id="local->ethernet->port1->rx_flow">128</span>
<span id="remote->id">128</span>
我需要通过 ID 从它们中创建多维数组 我需要的元素 q4234
数组的示例是 array["local"] 我创建的["ethernet"]["port3"]["rx_flow"]="q4234"
函数是:
function make_cfg(){
var result=new Array();
var x=document.getElementById(*);
var len=x.length;
var arr;
for (var i=0; i<=len; i++;){
if(x[i].id){
if(x[i].id.indexOf("->") != -1) {
arr=x[i].id.split("->");
result=make_obj(result,arr);
}
}
}
return result;
}
而且我不知道如何制作函数 make_obj()
<span id="local->ethernet->port3->rx_flow">q4234</span>
<span id="local->ethernet->port3->rx">q345</span>
<span id="local->ethernet->port1->rx_flow">128</span>
<span id="remote->id">128</span>
and I need to make multidimensional array from them by ID
example from element <span id="local->ethernet->port3->rx_flow">q4234</span>
array I need is array["local"]["ethernet"]["port3"]["rx_flow"]="q4234"
function I created is:
function make_cfg(){
var result=new Array();
var x=document.getElementById(*);
var len=x.length;
var arr;
for (var i=0; i<=len; i++;){
if(x[i].id){
if(x[i].id.indexOf("->") != -1) {
arr=x[i].id.split("->");
result=make_obj(result,arr);
}
}
}
return result;
}
And I have no idea how to make function make_obj()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不会为你写出全部内容,我只是帮助你解决一些困难的部分。
此代码段将采用两个字符串(基本上是
id
和innerHTML
,这里是s
和s2
)并构造一个嵌套的对象(Javascript 中没有关联数组)。它使用递归来实现其目标。如果您对代码有任何疑问,请询问。
在这里您可以尝试一下。
还需要做什么?
我猜你想将这些东西从跨度收集到一个对象中,我的示例将为每个
s
/s2< 创建一个对象/代码>。如果您还有任何疑问,我很乐意为您提供帮助。
I won't write the whole thing for you, I just help with the hard part a bit.
This snippet will take the two strings (basically
id
andinnerHTML
, heres
ands2
) and construct a nested object (there are no associative arrays in Javascript) out of it.It uses recursion to achieve its goal. If you have any questions about the code, please ask.
Here you can try it out.
What is left to do?
I guess you want to collect these things from the spans into ONE object, my example will create one object for every
s
/s2
. If you have any further questions, I am happy to help.这几乎有效(不像递归函数那么优雅)
http://jsfiddle.net/mplungjan/3zhwv/
缺少远程/id 中的 128,但其余部分有效。我想知道如何从小于 4 的节点获取 128
我同意它不像递归函数那样灵活,但我想看看是否可以先进行“暴力”,然后再进行 par它归结为更聪明的事情。
this almost worked (not so elegant as a recursive function)
http://jsfiddle.net/mplungjan/3zhwv/
Missing the 128 from the remote/id but the rest works. I would like to figure out what to do to get the 128 from the node that is shorter than 4
I agree it is not flexible like a recursive function, but I wanted to see if I could make a "brute force" first and then par it down to something more clever.